使用RestTemplate 请求微服务的时候,需要导入:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
Controller实现如下:
@RestController public class UserController { private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); @Autowired private UserFeignService userFeignService; @Autowired private LoadBalancerClient loadBalancerClient; @Autowired private RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "findByIdFallback") @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { return restTemplate.getForObject("http://spring-user-provider-eureka/" + id, User.class); } public User findByIdFallback(Long id) { User user = new User(); user.setId(-1L); user.setName("默认用户"); return user; } }
其中当restTemplate.getForObject请求微服务失败的时候,调用findByIdFallback方法,返回默认值; 注解@HystrixCommand的fallbackMethod属性的值是方法名, 说明远程失败的时候调用的方法;
注意: 在使用RestTemplate的时候,需要在启动类加上注解@EnableHystrix
使用feign的时候,导入如下依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
因为feign已经整合了hystrix,所以不用再导入hystrix的依赖,但是需要在appliation.yml配置文件中加入以下配置:
feign: hystrix: enabled: true
实现类如下:
@FeignClient(name = "spring-user-provider-eureka", fallback = UserFeignServiceFallback.class) public interface UserFeignService { @RequestMapping(value = "/{id}", method = RequestMethod.GET) User findById(@PathVariable("id") Long id); }
fallback属性指定调用失败的时候,调用的类,这里是UserFeignServiceFallback类,实现了UserFeignSerivce接口
@Component public class UserFeignServiceFallback implements UserFeignService { @Override public User findById(@PathVariable("id") Long id) { User user = new User(); user.setId(-2L); user.setName("Feign默认用户"); return user; } }(小白日记)么么哒