spring Cloud-Hystrix 进行服务保护
Hystrix的介绍
依赖:
<!--整合hystrix--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
设置回调函数:
修改ItemService的queryItemById方法
在要做容错处理的方法上加@HystrixCommand
注解,并指定一个容错方法,即fallbackMethod,服务失败时就会调用这个方法 。
/** * 进行容错处理 * fallbackMethod的方法参数个数类型要和原方法一致 * * @param id * @return */ @HystrixCommand(fallbackMethod = "queryItemByIdFallbackMethod") public Item queryItemById3(Long id) { String itemUrl = "http://app-item/item/{id}"; Item result = restTemplate.getForObject(itemUrl, Item.class, id); System.out.println("===========HystrixCommand queryItemById-线程池名称:" + Thread.currentThread().getName() + "订单系统调用商品服务,result:" + result); return result; } /** * 请求失败执行的方法 * fallbackMethod的方法参数个数类型要和原方法一致 * * @param id * @return */ public Item queryItemByIdFallbackMethod(Long id) { return new Item(id, "查询商品信息出错!", null, null, null); }
在启动类添加@EnableHystrix注解
@SpringBootApplication @EnableEurekaClient @EnableHystrix @ComponentScan(basePackages = {"com.zpc.order.controller", "com.zpc.order.service","com.zpc.order.properties"})//手动指定bean扫描范围 public class OrderApp { public static void main(String[] args) { SpringApplication.run(OrderApp.class, args); } /** * 向Spring容器中定义RestTemplate对象 * @return */ @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(new OkHttp3ClientHttpRequestFactory()); } }
在Controller增加一个入口,进行测试
package com.zpc.order.controller; import com.zpc.order.entity.Order; import com.zpc.order.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class OrderController { @Autowired private OrderService orderService; /** * 普通获取方法 没有注入Hystrix */ @GetMapping(value = "order/{orderId}") public Order queryOrderById(@PathVariable("orderId") String orderId) { return this.orderService.queryOrderById(orderId); } /** * 有注入Hystrix */ @GetMapping(value = "order2/{orderId}") public Order queryOrderById2(@PathVariable("orderId") String orderId) { return this.orderService.queryOrderByIdx(orderId); } }
OrderService中增加进行测试:
public Order queryOrderByIdx(String orderId) { Order order = ORDER_DATA.get(orderId); if (null == order) { return null; } List<OrderDetail> orderDetails = order.getOrderDetails(); for (OrderDetail orderDetail : orderDetails) { // 通过商品微服务查询带有Hystrix的商品详细数据查询接口 Item item = this.itemService.queryItemById3(orderDetail.getItem() .getId()); if (null == item) { continue; } orderDetail.setItem(item); } return order; }
调用能正常返回的Hystrix接口:
调用不能正常返回的Hystrix接口:
调用不能正常返回的普通接口:
转载自:https://blog.csdn.net/hellozpc/article/details/83692496