整合Hystrix
order-service
pom.xml
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
web层
1 @RestController 2 @RequestMapping("/api/v1/order") 3 public class OrderController { 4 5 6 @Autowired(required = false) 7 private ProductOrderServiceImpl productOrderService; 8 9 10 @RequestMapping("/save") 11 @HystrixCommand(fallbackMethod="saveOrderFail") 12 public Object save(@RequestParam("user_id")int userId, @RequestParam("product_id") int productId){ 13 14 Map<String, Object> data = new HashMap<>(); 15 data.put("code", 0); 16 data.put("data", productOrderService.save(userId, productId)); 17 return data; 18 } 19 20 //注意,方法签名一定要要和api方法一致 21 public Object saveOrderFail(int userId,int productId){ 22 23 Map<String, Object> msg = new HashMap<>(); 24 msg.put("code", -1); 25 msg.put("msg", "抢购人数太多,您被挤出来了,稍等重试"); 26 return msg; 27 } 28 29 30 }
application.yml
1 server: 2 port: 8781 3 4 5 #指定注册中心地址 6 eureka: 7 client: 8 serviceUrl: 9 defaultZone: http://localhost:8761/eureka/ 10 11 #服务的名称 12 spring: 13 application: 14 name: order-service 15 16 ###配置请求超时时间 17 hystrix: 18 command: 19 default: 20 execution: 21 isolation: 22 thread: 23 timeoutInMilliseconds: 7000 24 ribbon: 25 ##指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间。 26 ReadTimeout: 3000 27 ##指的是建立连接后从服务器读取到可用资源所用的时间。 28 ConnectTimeout: 3000 29 30 #自定义负载均衡策略 31 #product-service: 32 # ribbon: 33 # NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
product-service
service层
1 package com.topcheer.producerservice.controller; 2 3 import com.topcheer.producerservice.domain.Product; 4 import com.topcheer.producerservice.service.ProductService; 5 import org.springframework.beans.BeanUtils; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.beans.factory.annotation.Value; 8 import org.springframework.web.bind.annotation.*; 9 10 import java.util.concurrent.TimeUnit; 11 12 @RestController 13 @RequestMapping("/api/v1/product") 14 public class ProductController { 15 16 17 18 @Value("${server.port}") 19 private String port; 20 21 @Autowired 22 private ProductService productService; 23 24 /** 25 * 获取所有商品列表 26 * @return 27 */ 28 @RequestMapping("list") 29 public Object list(){ 30 return productService.listProduct(); 31 } 32 33 34 /** 35 * 根据id查找商品详情 36 * @param id 37 * @return 38 */ 39 @RequestMapping("find") 40 public Object findById(int id){ 41 42 try { 43 TimeUnit.SECONDS.sleep(2); 44 } catch (InterruptedException e) { 45 e.printStackTrace(); 46 } 47 Product product = productService.findById(id); 48 49 Product result = new Product(); 50 BeanUtils.copyProperties(product,result); 51 result.setName( result.getName() + " data from port="+port ); 52 return result; 53 } 54 55 }
结果:
当前面的ribbon配置3秒的时候,可以直接返回结果。
当前面的ribbon配置2秒的时候,会被HystrixCommand里面的异常方法捕获到。