java中使用FeignCilent远程调用Hystrix怎么做保护?
使用FeignClient远程调用时,可以在FeignClient中使用@HystrixCommand注解进行熔断器的保护。
具体步骤如下:
- 在FeignClient中添加@HystrixCommand注解,示例代码如下:
@FeignClient(name = "service-name", fallback = UserServiceFallback.class)
public interface UserService {
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod = "getUserFallback")
User getUser(@PathVariable("id") Long id);
default User getUserFallback(Long id) {
return new User();
}
}
-
在fallbackMethod属性中指定该方法调用失败时的备选方法,该方法应该返回一个指定类型的默认值,示例代码中返回了一个新的User对象。
-
在启动类中添加@EnableHystrix注解开启Hystrix支持。
@SpringBootApplication
@EnableHystrix
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这样,在调用FeignClient时,如果服务调用失败,会自动调用fallbackMethod指定的备选方法,从而保护应用程序不会因为服务调用失败而崩溃。
原文地址: http://www.cveoy.top/t/topic/bgFG 著作权归作者所有。请勿转载和采集!