使用Hystrix的FallbackFactory统一的熔断处理同时将异常处理和业务解耦,避免使用@HystrixCommand,导致熔断处理方法不断膨胀

首先写一个类实现FallbackFactory, T的类型为具体的XXXFeign 

package cn.cuit.user.center.service.hystrix;

import org.springframework.stereotype.Component;

import cn.cuit.product.center.api.domian.Product;
import cn.cuit.user.center.service.feign.UserCenterProductFeign;
import feign.hystrix.FallbackFactory;

@Component  // 一定要把组件纳入Spring管理,才能使用Spring的一系列的功能和特性
public class UserHystrixFallbackFactory implements FallbackFactory{

	@Override
	public UserCenterProductFeign create(Throwable cause) {
		return new UserCenterProductFeign() {
			@Override
			public String sum(Integer a, Integer b) {
				// do Sth
				return null;
			}
			
			@Override
			public Product getProductById(String id) {
				// do Sth
				return null;
			}
		};
	}

}

 在Feign上配置上面的的处理Factory

package cn.cuit.user.center.service.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.cuit.product.center.api.domian.Product;
import cn.cuit.user.center.service.hystrix.UserHystrixFallbackFactory;

/**
 * Feign Client
 */
@FeignClient(value = "cuit-product-center-service", fallbackFactory = UserHystrixFallbackFactory.class)
public interface UserCenterProductFeign {


	@RequestMapping(value = "/product-service/api/products/testFeign", method = RequestMethod.GET)
	public String sum(@RequestParam Integer a, @RequestParam Integer b);


	@GetMapping("/product-service/api/products/getProductById/{id}")
	public Product getProductById(@PathVariable("id") String id);
}

启动类上开启熔断器

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker  // 开启熔断
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

 

********************************* 不积跬步无以至千里,不积小流无以成江海 *********************************

你可能感兴趣的:(SpringCloud)