Details of springcloud Feign Hystrix support
- 2021-01-03 20:55:45
- OfStack
This article introduces springcloud Feign's Hystrix support and shares it with you as follows:
1. fallback added to Feign client
@FeignClient(name="springboot-h2", fallback=HystrixClientFallback.class) // in fallback Property that specifies a circuit breaker fallback
public interface UserFeignClient {
// @GetMapping("/user/{id}")
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
User findById(@PathVariable("id") Long id);
@RequestMapping(value="/users", method=RequestMethod.GET)
List<User> findAll();
@RequestMapping(value="/post/user", method=RequestMethod.POST)
User save(@RequestBody User user);
}
2. Write HystrixClientFallback classes
@Component // join spring bean In the
public class HystrixClientFallback implements UserFeignClient{
@Override
public User findById(Long id) {
User u = new User();
u.setName(" Temporary name ");
u.setUsername(" anonymous ");
return u;
}
@Override
public List<User> findAll() {
return null;
}
@Override
public User save(User user) {
return null;
}
}
3. Join Hystrix support
@EnableCircuitBreaker
4. Test
Instead of starting the underlying dependent service, start the service directly, and then test it. The result found in the browser is:
[
{" id ": null," username ":" anonymous ", and "name" : "temporary name", "age" : null, "balance" : null}
Instead of reporting an exception as expected, it goes into the findById method in the HystrixClientFallback class.