spring cloud: Hystrix(六):feign的注解@FeignClient:fallbackFactory(类似于断容器)与fallback方法
fallbackFactory(类似于断容器)与fallback方法
feign的注解@FeignClient:fallbackFactory与fallback方法不能同时使用,这个两个方法其实都类似于Hystrix的功能,当网络不通时返回默认的配置数据.
fallback方法的使用:
在入口文件开启feign注解功能。
@EnableFeignClients
@EnableEurekaClient @SpringBootApplication @EnableFeignClients public class FeignApp { public static void main(String[] args) { SpringApplication.run(FeignApp.class, args); } }
2.写一个访问spring-boot-user服务的接口,同时在@FeignClient注解中使用fallback默认返回方法(断容器)
fallback=HystrixClientFallback.class
@FeignClient(name="spring-boot-user", fallback=HystrixClientFallback.class) public interface UserFeignClient { // 两个坑:1. @GetMapping不支持 2. @PathVariable得设置value @RequestMapping(value="/simple/{id}", method=RequestMethod.GET) public User findById(@PathVariable("id") Long id); }
3.写HystrixClientFallback类,并继承UserFeignClient类,当网络不通或者访问失败时,返回固定/默认内容
@Component public class HystrixClientFallback implements UserFeignClient{ @Override public User findById(Long id) { // TODO Auto-generated method stub User user = new User(); user.setId(0L); return user; } }
4.controller调用spring-boot-user服务的接口
@RestController public class MovieController { @Autowired private UserFeignClient userFeignClient; @GetMapping("/movie/{id}") public User findById(@PathVariable("id") Long id) { return this.userFeignClient.findById(id); } }
fallbackFactory方法的使用
1.入口文件引入feign注解
@EnableEurekaClient @SpringBootApplication @EnableFeignClients public class FeignApp { public static void main(String[] args) { SpringApplication.run(FeignApp.class, args); } }
2.写feignClient客户端j,使用feignClient注解的fallbackFactory方法
@FeignClient(name="spring-boot-user", fallbackFactory=HystrixClientFallbackFactory.class) public interface UserFeignClient { // 两个坑:1. @GetMapping不支持 2. @PathVariable得设置value @RequestMapping(value="/simple/{id}", method=RequestMethod.GET) public User findById(@PathVariable("id") Long id); }
3.写HystrixClientFallbackFactory类,和HystrixClientWithFallbackFactory类
HystrixClientWithFallbackFactory类继承UserFeignClient类
public interface HystrixClientWithFallbackFactory extends UserFeignClient { }
HystrixClientFallbackFactory实现FallbackFactory类,并使用内部匿名方法类,继续UserFeignClient
@Component public class HystrixClientFallbackFactory implements FallbackFactory<UserFeignClient> { @Override public UserFeignClient create(Throwable arg0) { // TODO Auto-generated method stub return new HystrixClientWithFallbackFactory() { @Override public User findById(Long id) { // TODO Auto-generated method stub User user = new User(); user.setId(-1L); return user; } }; } }
4controller调用UserFeignClient接口
@RestController public class MovieController { @Autowired private UserFeignClient userFeignClient; @GetMapping("/movie/{id}") public User findById(@PathVariable("id") Long id) { return this.userFeignClient.findById(id); } }
5调用
当开启spring-boot-user方法,返回数据
当关闭spring-boot-user服务时