背景
爲了防止下游服務雪崩,這裏考慮使用斷路器
技術選型
由於是springboot服務且集成了istio,這裏考慮三種方案
- istio
- hystrix
- sentinel
這裏分別有這幾種方案的對比
微服務斷路器模式實現:Istio vs Hystrix
Sentinel 與 Hystrix 的對比
首先考慮的是istio,但是在使用istio進行熔斷、分流時,流量不穩定,並且返回狀態以及數據達不到預取效果,後面考慮到sentinel自動集成了grpc,所以這裏使用sentinel。
步驟
1、增加相關依賴
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-grpc-adapter</artifactId>
<version>1.7.1</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2、增加配置類
方案一:增加全局攔截器
/**
* @Auther: lipeng
* @Date: 2020/3/23 17:24
* @Description:
*/
@Order(Ordered.LOWEST_PRECEDENCE)
@Configuration
@Slf4j
public class SentinelConfig {
@Bean
public ClientInterceptor sentinelGrpcClientInterceptor(){
return new SentinelGrpcClientInterceptor();
}
@Bean
public GlobalClientInterceptorConfigurer globalInterceptorConfigurerAdapter(ClientInterceptor sentinelGrpcClientInterceptor) {
return registry -> registry.addClientInterceptors(sentinelGrpcClientInterceptor);
}
}
方案二:調用時增加攔截器
當然這裏也可以換一種方式增加攔截器,如下,在啓動類中增加
@Bean
public ClientInterceptor sentinelGrpcClientInterceptor(){
return new SentinelGrpcClientInterceptor();
}
然後在調用類中增加依賴
@Autowired
private ClientInterceptor sentinelGrpcClientInterceptor;
public void doXXX(){
XXXGrpc.XXXBlockingStub stub = XXXGrpc.newBlockingStub(serverChannel).withInterceptors(sentinelGrpcClientInterceptor);
XXXApi.XXXResponse response = stub.withDeadlineAfter(grpcTimeout, TimeUnit.MILLISECONDS).doXXX(request);
}
3、增加sentinel dashboard配置
spring:
cloud:
sentinel:
transport:
port: 8719
dashboard: localhost:7080
4、部署sentinel dashboard
部署參考下面鏈接:
啓動後訪問下相關鏈接,grpc自動集成上去了,效果如下:
詳細配置可以參考官方wiki:https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8