在上一篇博客搭建的项目基础上:https://blog.csdn.net/qq_41890624/article/details/103663817
首先在parent的pom.xml 中添加Hystrix相关依赖
<!-- hystrix断路器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在order-service-impl 项目的配置文件中添加开启Hystrix
feign:
hystrix:
enabled: true
在项目的OrderServiceImpl类中添加三个方法测试
package com.vhukze.order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.vhukze.api.entity.UserEntity;
@RestController
public class OrderServiceImpl implements IOrderService{
@Autowired
private MemberServiceFeign feign;
@RequestMapping("toMember")
public String toMember(String name) {
// TODO Auto-generated method stub
System.out.println("当前线程名称:"+Thread.currentThread().getName());
UserEntity user = feign.getMember(name);
return user.toString();
}
@RequestMapping("toMemberHystrix")
@HystrixCommand(fallbackMethod="fallbackMethod")
//此注解默认开启服务熔断、服务降级(指定降级使用的方法名称)、线程池隔离
public String toMemberHystrix(String name) {
// TODO Auto-generated method stub
System.out.println("当前线程名称:"+Thread.currentThread().getName());
UserEntity user = feign.getMember(name);
return user.toString();
}
public String fallbackMethod(String data) {
return "服务降级,稍后重试";
}
}
fallbackMethod指定的方法需要带一个参数,不然会报错fallback method wasn't found: fallbackMethod([class java.lang.String])
现在访问http://localhost:8020/toMemberHystrix?name=22会出现服务降级的提示,因为getMember 方法中设置了线程等待1.5秒。Hystrix超时时间没有设置。
设置Hystrix的超时时间
#### hystrix禁止服务超时时间
hystrix:
command:
default:
execution:
timeout:
enabled: false
此时可以正常访问。
然后我们使用压力测试工具Jmeter设置200个线程循环访问访问http://localhost:8020/toMemberHystrix?name=22
再使用浏览器访问该接口,便会出现服务降级,稍后重试的字样。
但是访问http://localhost:8020/toMember?name=22还是可以正常访问,说明开启了线程池隔离机制。