简介
- 为了实现对后端服务中feign调用接口和第三方调用接口的降级、限流,后端服务中引入了阿里的sentinel,Sentinel中文意思是哨兵。通过在相关方法、类上加相关注解,便能实现对相关方法的限流、降级。下面具体介绍后端服务引入Sentinel的具体步骤。
1. POM中添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
2. YML文件增加配置
spring:
cloud:
sentinel:
eager: true #提前触发Sentinel初始化,使得服务启动后便可通过Sentinel控制台查看
transport:
port: 8722
dashboard: ${sentinel_dashboard_address:} #Sentinel控制台地址,如:localhost:8080
log:
dir: ${log.logDir:.logs}/sentinel
3. 添加注解
3.1 在方法上
添加注解:@SentinelResource
,如下所示:
@SentinelResource(value = "testFallBack",blockHandler = "testHandler", blockHandlerClass = {TestFallback.class})
@GetMapping("/test")
public ResponseEntity<String> test(){
return ResponseEntity.success("success");
}
类TestFallback中
定义方法testHandler
,如下所示:
在添加晚上述注解部署服务后,便可以在Sentinel的dashboard中看到名为testFallBack的资源名。
3.2 在Feign调用接口上
- POM文件中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- YML文件中添加:
feign:
sentinel:
enabled: true
- 在Feign接口上添加注解``
@FeignClient(value = "${feign调用服务名}",fallback = TestFallback.class, configuration = TestConfig.class)
TestFallback类需要实现当前的Feign接口类。
在TestConfig类中定义Bean:
@Bean
public TestFallback echoTestFallback(){
return new TestFallback();
}