1、创建一个maven项目 hystrix-ribbon-semaphore-consumer
pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
application.yml
spring:
application:
name: hystrix-ribbon-semaphore-consumer
server:
port: 8082
eureka:
client:
serviceUrl:
defaultZone: http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
instance:
prefer-ip-address: true #默认是hostname注册,改成IP注册
2、创建隔离服务类,服务类调用eureka-provider这个项目提供的生产者
@Service
public class StudentService {
@Autowired
private LoadBalancerClient loadBalancerClient;
/**
* 配置当并发高的时候服务降级,并返回拖底数据,防止服务雪崩
* @return
*/
@HystrixCommand(fallbackMethod="fallback",
commandProperties = {
//信号量隔离
@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "SEMAPHORE"),
//信号量最大并发度
@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "100")
})
public List<Student> studentList() {
// 获取服务端
ServiceInstance si = loadBalancerClient.choose("eureka-provider");//EUREKA-PROVIDER
// 拼装服务端地址
StringBuffer pUrl = new StringBuffer();
pUrl.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/list");
ParameterizedTypeReference<List<Student>> typeRef = new ParameterizedTypeReference<List<Student>>() {};
//远程调用获取提供者的数据
RestTemplate rt = new RestTemplate();
ResponseEntity<List<Student>> resp = rt.exchange(pUrl.toString(), HttpMethod.GET, null, typeRef);
List<Student> studentList = resp.getBody();
return studentList;
}
/**
* fallback返回拖底数据
* 以下四种情况将触发getFallback调用
* 1、方法抛出非HystrixBadRequestException异常。
* 2、方法调用超时
* 3、熔断器开启拦截调用
* 4、线程池/队列/信号量是否跑满
* @return
*/
public List<Student> fallback(){
List<Student> list = new ArrayList<Student>();
list.add(new Student("fallback",-1));
return list;
}
}
3、创建一个测试类
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("list")
public List<Student> list(){
return studentService.studentList();
}
}