在微服务架构中,我们将系统拆分成了一个个的服务单元,各单元应用间通过服务注册与订阅的方式互相依赖。由于每个单元都在不同的进程中运行,依赖通过远程调用的方式执行,这样就有可能因为网络原因或是依赖服务自身问题出现调用故障或延迟,而这些问题会直接导致调用方的对外服务也出现延迟,若此时调用方的请求不断增加,最后就会出现因等待出现故障的依赖方响应而形成任务积压,线程资源无法释放,最终导致自身服务的瘫痪,进一步甚至出现故障的蔓延最终导致整个系统的瘫痪。如果这样的架构存在如此严重的隐患,那么相较传统架构就更加的不稳定。为了解决这样的问题,因此产生了断路器等一系列的服务保护机制。
针对上述问题,在Spring Cloud Hystrix中实现了线程隔离、断路器等一系列的服务保护功能。它也是基于Netflix的开源框架 Hystrix实现的,该框架目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix具备了服务降级、服务熔断、线程隔离、请求缓存、请求合并以及服务监控等强大功能。
实现:服务消费者中都放入断路器
1.引入依赖
首先我们需要引入断路器的依赖:
<!-- hystrix :断路器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.主入口:接下来我们可以使用注解@EnableCircuitBreaker //开启断路器功能
package com.zx.dt2b;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.web.client.RestTemplate;
/**
* Author:码图科技
* Date:2018至今
* 作为服务消费者存在
* Description:版权所有,违者必究
*/
@EnableCircuitBreaker //1.开启断路器的功能
@EnableDiscoveryClient //标识具体的一个服务,需要向注册中心注册
@SpringBootApplication //SpringBoot 核心配置
@EnableRetry //开启重试
public class ErpApplication {
/* @Bean
@LoadBalanced //用于实现内部的服务负载均衡机制: service-id service-name// 如果加了这个注解 , 那么就说明 具有了服务发现的特性 负载均和的机制:意味着可以通过服务名请求数据
public RestTemplate restTemplate(){
HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpComponentsClientHttpRequestFactory.setConnectTimeout(10000);
httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(10000);
httpComponentsClientHttpRequestFactory.setReadTimeout(20000);
return new RestTemplate(httpComponentsClientHttpRequestFactory);
}*/
@Bean
@ConfigurationProperties(prefix = "custom.requestFactory")
public HttpComponentsClientHttpRequestFactory customHttpRequestFactory(){
return new HttpComponentsClientHttpRequestFactory();
}
@Bean
@LoadBalanced //用于实现内部的服务负载均衡机制: service-id service-name
public RestTemplate restTemplate(){
return new RestTemplate(customHttpRequestFactory());
}
public static void main(String[] args) {
SpringApplication.run(ErpApplication.class, args);
}
}
3.配置文件:配置断路器的超时时间,默认是1秒:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 10000
4.业务代码中应用断路器:
@HystrixCommand注解中:
服务调用失败调用对应方法 callhelloFailback(); fallbackMethod = "callhelloFailback"比如,如果某个数据错误,失败后进行后续处理。
请求时候,接口超时异常走降级服务:
请求异常走降级服务:类似于在服务调用时出现的异常:主动抛异常/或者代码逻辑有异常
分析:指定服务超时降级
配置文件中设置的是整体默认的超时时间;
下面参数能够设置某个服务接口的超时时间:
commandKey:服务接口
commandProperties:时间参数
@HystrixCommand(fallbackMethod = "timeoutFailback",
commandKey = "helloKey",
commandProperties ={
@HystrixProperty(name="execution.timeout.enabled", value="true"),
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="3000")
}
)
比如还可以单独设置某个服务的http调用断路器超时时间等:使用commandKey与commandProperties属性相互结合使用,可以单独的控制特殊需求的实现。
/**
* 在服务的内部指定一个超时时间配置:
* 一般来讲 我们需要设置一个全局的默认断路器超时时间,如果有需要会在具体的服务上去单独设置超时时间
* @return
*/
@HystrixCommand(fallbackMethod = "timeoutFailback",
commandKey = "helloKey",
commandProperties ={
@HystrixProperty(name="execution.timeout.enabled", value="true"),
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="3000")
}
)
public String callhello4timeout(){
String ret= restTemplate.getForObject("http://provider-service/hello", String.class);
System.err.println("hello service ret: " + ret);
return ret;
}
分析:请求合并
批次处理请求合并:比如短时间内有很多人获取自己的用户信息,有效的节省了网络请求次数。
需要服务提供者底层写查询单个对象接口以及查询批量接口:
/**
* 单独查询User接口
* 使用rest风格path传递参数
* @param id
* @return
* @throws Exception
*/
// http://localhost:7001/users/1
@RequestMapping(value="/users/{id}")
public User getUser(@PathVariable String id) throws Exception {
System.err.println("provider-1 单独查询-------> " + id);
return new User("1", "张三");
}
/**
* 批量查询users接口
* @param ids
* @return
* @throws Exception
*/
@RequestMapping(value="/users")
public List<User> getUsers(@RequestParam("ids") String ids) throws Exception {
System.err.println("provider-1 批量查询-------> " + ids);
List<User> users = new ArrayList<>();
users.add(new User("2", "张四"));
users.add(new User("3", "张五"));
users.add(new User("4", "张六"));
users.add(new User("5", "张七"));
return users;
}
@HystrixCollapser(batchMethod="findAll",
collapserProperties = {
@HystrixProperty(name="timerDelayInMilliseconds", value="200"), //单个请求的延迟时间
@HystrixProperty(name="maxRequestsInBatch", value="50"), //允许最大的合并请求数量
@HystrixProperty(name="requestCache.enabled", value="false") //是否允许开启请求的本地缓存(对于一些静态数据可以进行启用)
}
)
200毫秒内如果有大量请求,50个请求进行批处理,不会将请求缓存,如果静态数据可以开启缓存
消费端业务调用代码:返回Future<User>不做任何实现,batchMethod对应的方法会将合并的ids进行处理。
/**
* 使用hystrix的批量合并请求功能
*
*/
@HystrixCollapser(batchMethod="findAll",
collapserProperties = {
@HystrixProperty(name="timerDelayInMilliseconds", value="200"), //单个请求的延迟时间
@HystrixProperty(name="maxRequestsInBatch", value="50"), //允许最大的合并请求数量
@HystrixProperty(name="requestCache.enabled", value="false") //是否允许开启请求的本地缓存(对于一些静态数据可以进行启用)
}
)
public Future<User> find(String id){
return null;
}
@HystrixCommand
public List<User> findAll(List<String> ids) {
System.err.println("合并请求线程操作: --------> " + Thread.currentThread().getName());
List<User> users = restTemplate.getForObject("http://customer-service/customerservice/users?ids={1}", List.class, StringUtils.join(ids, ","));
return users;
}
模拟批量请求:
实际上该方法只会调一个Future<User> f1 = helloService.find("1");
@RequestMapping(value="/hystrix-batch")
public String batch() throws Exception {
HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
Future<User> f1 = helloService.find("1");
Future<User> f2 = helloService.find("2");
Future<User> f3 = helloService.find("3");
Future<User> f4 = helloService.find("4");
System.err.println(f1.get());
System.err.println(f2.get());
System.err.println(f3.get());
System.err.println(f4.get());
Thread.sleep(1000);
Future<User> f5 = helloService.find("5");
System.err.println(f5.get());
ctx.close();
return "batch success!";
}
分析:现程池隔离的策略
THREAD 通过现程池隔离的策略,它会独立在一个线程上执行,并且他的并发量受线程池中的数量所限制。
queueSizeRejectionThreshold=30,限制了并发量超出并发后执行threadFailback定义的方法,一般返回静态资源,入网络忙。
所有限流只对该服务有影响,对下游服务器没有直接影响
@HystrixCommand(
commandKey = "threadKey1",
/*使用commandProperties --> execution.isolation.strategy 指定限流的策略 也可以省略*/
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="THREAD")
},
threadPoolKey = "threadPoolKey1",
threadPoolProperties = {
//核心线程数,最大的并发线程数量
@HystrixProperty(name="coreSize", value="10"),
//因为底层机制使用的是有界队列,有界队列必须要指定队列的容量上限.当一旦指定容量上限后就不能进行动态的调整
@HystrixProperty(name="maxQueueSize", value="2000"),
//使用THREAD方式: 关键的服务降级指标, 设置拒绝的阈值(可以动态的进行调整)
@HystrixProperty(name="queueSizeRejectionThreshold", value="30")
},
fallbackMethod="threadFailback"
)
服务提供者代码
@RequestMapping(value="/thread")
public String thread() throws Exception {
System.err.println("provider2: ---------> thread" );
Thread.sleep(RandomUtils.nextInt(100, 500));
return "provider2";
}
服务消费者代码
/**
* Hystrix实现限流机制: 使用THREAD方式: 线程池的方式进行隔离限流策略
*/
@HystrixCommand(
commandKey = "threadKey1",
/*使用commandProperties --> execution.isolation.strategy 指定限流的策略 也可以省略*/
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="THREAD")
},
threadPoolKey = "threadPoolKey1",
threadPoolProperties = {
//核心线程数,最大的并发线程数量
@HystrixProperty(name="coreSize", value="10"),
//因为底层机制使用的是有界队列,有界队列必须要指定队列的容量上限.当一旦指定容量上限后就不能进行动态的调整
@HystrixProperty(name="maxQueueSize", value="2000"),
//使用THREAD方式: 关键的服务降级指标, 设置拒绝的阈值(可以动态的进行调整)
@HystrixProperty(name="queueSizeRejectionThreshold", value="30")
},
fallbackMethod="threadFailback"
)
public String thread(){
String ret = restTemplate.getForObject("http://provider-service/thread", String.class);
System.err.println("输出调用结果: " + ret);
return ret;
}
开放接口
@RequestMapping(value="/hystrix-thread")
public String thread() throws Exception {
return this.helloService.thread();
}
代码实现后,采用jmete实现测试功能
分析:信号量策略
execution.isolation.strategy指定限流的策略。线程策略可以不写SEMAPHORE信号量策略必须写
execution.isolation.semaphore.maxConcurrentRequests最大允许并发数(请求个数),限流后走fallbackMethod定义的接口。一般是传递静态资源,比如网络忙。
@HystrixCommand(
commandKey ="semaphoreKey1",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE"),
@HystrixProperty(name="execution.isolation.semaphore.maxConcurrentRequests", value="10") //某一时间最大允许并发请求个数
},
fallbackMethod="semaphoreFailback"
)
服务提供者代码
@RequestMapping(value="/semaphore")
public String semaphore() throws Exception {
System.err.println("provider2: ---------> semaphore" );
Thread.sleep(RandomUtils.nextInt(100, 500));
return "provider2";
}
服务消费者代码
/**
* Hystrix实现限流机制: 使用SEMAPHORE方式: 使用java.util.concurrent.SEMAPHORE
*/
@HystrixCommand(
commandKey ="semaphoreKey1",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE"),
@HystrixProperty(name="execution.isolation.semaphore.maxConcurrentRequests", value="10") //某一时间最大允许并发请求个数
},
fallbackMethod="semaphoreFailback"
)
public String semaphore(){
String ret = restTemplate.getForObject("http://provider-service/semaphore", String.class);
System.err.println("输出调用结果: " + ret);
return ret;
}
开放接口:
@RequestMapping(value="/hystrix-semaphore")
public String semaphore() throws Exception {
return this.helloService.semaphore();
}
实现后,用jemete测试请求
服务消费者:组合代码
package com.zx.dt2b.service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zx.dt2b.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.concurrent.Future;
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
/**
* 服务超时调用异常(服务的调用方)
* @return
*/
@HystrixCommand(fallbackMethod = "callhelloFailback")
public String callhello(){
String ret= restTemplate.getForObject("http://provider-service/hello", String.class);
System.err.println("hello service ret: " + ret);
return ret;
}
public String callhelloFailback(){
return "hello服务调用失败,进降级处理!!";
}
/**
* 服务内部异常(被调用方)
* @return
*/
@HystrixCommand(fallbackMethod = "callhiFailback")
public String callhi() {
String ret = restTemplate.getForObject("http://provider-service/hi", String.class);
System.err.println("hi service ret: " + ret);
return null;
}
public String callhiFailback(){
return "hi服务调用失败,进降级处理!!";
}
/**
* 在服务的内部指定一个超时时间配置:
* 一般来讲 我们需要设置一个全局的默认断路器超时时间,如果有需要会在具体的服务上去单独设置超时时间
* @return
*/
@HystrixCommand(fallbackMethod = "timeoutFailback",
commandKey = "helloKey",
commandProperties ={
@HystrixProperty(name="execution.timeout.enabled", value="true"),
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="3000")
}
)
public String callhello4timeout(){
String ret= restTemplate.getForObject("http://provider-service/hello", String.class);
System.err.println("hello service ret: " + ret);
return ret;
}
public String timeoutFailback(){
return "在callhello4timeout服务接口上指定超时时间,调用失败,进降级处理!!";
}
/**
* 使用hystrix的批量合并请求功能
*
*/
@HystrixCollapser(batchMethod="findAll",
collapserProperties = {
@HystrixProperty(name="timerDelayInMilliseconds", value="200"), //单个请求的延迟时间
@HystrixProperty(name="maxRequestsInBatch", value="50"), //允许最大的合并请求数量
@HystrixProperty(name="requestCache.enabled", value="false") //是否允许开启请求的本地缓存(对于一些静态数据可以进行启用)
}
)
public Future<User> find(String id){
return null;
}
@HystrixCommand
public List<User> findAll(List<String> ids) {
System.err.println("合并请求线程操作: --------> " + Thread.currentThread().getName());
List<User> users = restTemplate.getForObject("http://provider-service/users?ids={1}", List.class, StringUtils.join(ids, ","));
return users;
}
/**
* Hystrix实现限流机制: 使用THREAD方式: 线程池的方式进行隔离限流策略
*/
@HystrixCommand(
commandKey = "threadKey1",
/*使用commandProperties --> execution.isolation.strategy 指定限流的策略 也可以省略*/
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="THREAD")
},
threadPoolKey = "threadPoolKey1",
threadPoolProperties = {
//核心线程数,最大的并发线程数量
@HystrixProperty(name="coreSize", value="10"),
//因为底层机制使用的是有界队列,有界队列必须要指定队列的容量上限.当一旦指定容量上限后就不能进行动态的调整
@HystrixProperty(name="maxQueueSize", value="2000"),
//使用THREAD方式: 关键的服务降级指标, 设置拒绝的阈值(可以动态的进行调整)
@HystrixProperty(name="queueSizeRejectionThreshold", value="30")
},
fallbackMethod="threadFailback"
)
public String thread(){
String ret = restTemplate.getForObject("http://provider-service/thread", String.class);
System.err.println("输出调用结果: " + ret);
return ret;
}
public String threadFailback(){
System.err.println("--------thread限流,降级策略!--------");
return "--------thread限流,降级策略!--------";
}
/**
* Hystrix实现限流机制: 使用SEMAPHORE方式: 使用java.util.concurrent.SEMAPHORE
*/
@HystrixCommand(
commandKey ="semaphoreKey1",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE"),
@HystrixProperty(name="execution.isolation.semaphore.maxConcurrentRequests", value="10") //某一时间最大允许并发请求个数
},
fallbackMethod="semaphoreFailback"
)
public String semaphore(){
String ret = restTemplate.getForObject("http://provider-service/semaphore", String.class);
System.err.println("输出调用结果: " + ret);
return ret;
}
public String semaphoreFailback(){
System.err.println("--------semaphore限流,降级策略!--------");
return "--------semaphore限流,降级策略!--------";
}
}
5.控制层代码
package com.bfxy.springcloud.api;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bfxy.springcloud.entity.User;
import com.bfxy.springcloud.service.HelloService;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
@RestController
public class ConsumerController {
@Autowired
private HelloService helloService;
@RequestMapping(value="/hystrix-hello")
public String hello() throws Exception {
return helloService.callhello();
}
@RequestMapping(value="/hystrix-hi")
public String hi() throws Exception {
return helloService.callhi();
}
@RequestMapping(value="/hystrix-hello-timeout")
public String hellotimeout() throws Exception {
return helloService.callhello4timeout();
}
@RequestMapping(value="/hystrix-batch")
public String batch() throws Exception {
HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
Future<User> f1 = helloService.find("1");
Future<User> f2 = helloService.find("2");
Future<User> f3 = helloService.find("3");
Future<User> f4 = helloService.find("4");
System.err.println(f1.get());
System.err.println(f2.get());
System.err.println(f3.get());
System.err.println(f4.get());
Thread.sleep(1000);
Future<User> f5 = helloService.find("5");
System.err.println(f5.get());
ctx.close();
return "batch success!";
}
@RequestMapping(value="/hystrix-thread")
public String thread() throws Exception {
return this.helloService.thread();
}
@RequestMapping(value="/hystrix-semaphore")
public String semaphore() throws Exception {
return this.helloService.semaphore();
}
}
6.断路器的其他应用:
断路器的隔离策略很好的实现了限流
缓存功能:缓存请求结果
批量请求合并的功能:节省了http访问的次数
再比如断路器执行的隔离策略,对应着并发量剧增的场景下使用限流的方式,比传统的限流策略、限流组件有天然的优势。
还有强大的缓存功能,可以结合着spring cache配合使用 缓存http请求的结果。
断路器为我们提供了批量请求合并的功能,可以将多少频率的http请求批量合并在一起,发送一个http请求到对应的服务端,节省了http访问的次数,在超高频访问的场景中非常的有效。
7.请求合并:
当设定的时间内,将一批请求合并成一个请求走批量查询对策接口。
8.高并发限流系统/限流组件应用:
在断路器的配置限流策略中,execution.isolation.strategy 有两种方式进行处理:
THREAD 通过现程池隔离的策略,它会独立在一个线程上执行,并且他的并发量受线程池中的数量所限制。
SEMAPHONE 它则实现在调用的线程上,通过信号量的方式进行隔离,这种则是类似java中的限流了,受到信号量计数器的限制所约束。