Rest实现服务熔断
(1)复制 shop_service_order 项目并命名为 shop_service_order_rest_hystrix#
略
(2)配置依赖#
在 shop_service_order_rest_hystrix 工程中添加Hystrix的相关依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
(3)开启熔断#
在启动类 OrderApplication 中添加 @EnableCircuitBreaker 注解开启对熔断器的支持。
@EntityScan("cn.itcast.entity") //@EnableCircuitBreaker //开启熔断器 //@SpringBootApplication @SpringCloudApplication public class OrderApplication { //创建RestTemplate对象 @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }
可以看到,我们类上的注解越来越多,在微服务中,经常会引入上面的三个注解,于是Spring就提供了一个组合注解:@SpringCloudApplication
(4)配置熔断降级业务逻辑#
@RestController @RequestMapping("/order") public class OrderController { @Autowired private RestTemplate restTemplate; //下订单 @GetMapping("/product/{id}") @HystrixCommand(fallbackMethod = "orderFallBack") public Product findProduct(@PathVariable Long id) { return restTemplate.getForObject("http://shop-service- product/product/1", Product.class); } //降级方法 public Product orderFallBack(Long id) { Product product = new Product(); product.setId(-1l); product.setProductName("熔断:触发降级方法"); return product; } }
有代码可知,为 findProduct 方法编写一个回退方法fifindProductFallBack,该方法与 findProduct 方法具有相同的参数与返回值类型,该方法返回一个默认的错误信息。
在 Product 方法上,使用注解@HystrixCommand的fallbackMethod属性,指定熔断触发的降级方法是 findProductFallBack 。
因为熔断的降级逻辑方法必须跟正常逻辑方法保证:相同的参数列表和返回值声明。
在 findProduct 方法上 HystrixCommand(fallbackMethod = "findProductFallBack") 用来声明一个降级逻辑的方法
当 shop-service-product 微服务正常时,浏览器访问 http://localhost:9001/order/product/1
可以正常调用服务提供者获取数据。当将商品微服务停止时继续访问
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)