Spring Cloud Alibaba Sentinel 是阿里巴巴提供的,致力于提供微服务一站式解决方案,这篇文章主要介绍了Sentinel 之 整合SpringCloud的相关知识,需要的朋友可以参考下
正文
Sentinel 整合SpringCloud的详细教程
Spring Cloud Alibaba Sentinel 是阿里巴巴提供的,致力于提供微服务一站式解决方案,Spring Cloud Alibaba 默认为 Sentinel 整合了,ServeLet、RestTemplate、FeignClient 和 Spring Flux。在 Spring 的生态中不仅不全了 Hystrix 在 ServeLet 和 RestTemplate 这一块的空白,而且还完美的兼容了 Hystrix 在 Feign 中的限流降级用法,并支持运行时灵活的配置和调整限流降级规则。
引入依赖:
|
1
2
3
4
5
6
|
<!--Sentinel 整合SpringCloud 的依赖--><dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel</artifactId> <version>2.2.0.RELEASE</version></dependency> |
配置文件:
(入门使用中,应用名称使用的 JVM 参数设置的,整合 SpringCloud 就不需要那样了,配置文件中配置了应用的名称后,Sentinel 会自动加载)
|
1
2
3
4
5
6
7
8
9
10
|
# 设置应用的名称spring: application: name: springCloudSentinel cloud: sentinel: transport: #设置Sentinel控制台的主机地址和端口号 dashboard: localhost:9000 |
编写测试 Controller ,控制台添加 Sentinel_Cloud 资源 限流测试
|
1
2
3
4
5
6
|
@SentinelResource(value = "Sentinel_Cloud",blockHandler = "exceptionHandler")@GetMapping("/sentinelCloud")public String sentinelCloud(){ //使用限流规则 return "Sentinel_Cloud,成功调用";} |
限流时调用的方法:
|
1
2
3
4
5
6
7
8
9
10
|
/** * 定义降级 / 限流 的处理函数 * * @param exception * @return */public String exceptionHandler(BlockException exception) { exception.printStackTrace(); return "Sentinel_Cloud,访问限流";} |
Sentinel整合Feign (OpenFeign)
Sentinel适配了Feign组件。如果想要使用,除了引用spring-cloud-starter-alibaba-sentinel的依赖,还需要两个步骤:
配置打开Sentinel对Feign的支持:feign.sentinel.enable=true
加入spring-cloud-starter-openfeign依赖使Sentinel starter自动化配置类生效。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# 设置应用的名称spring: application: name: springCloudSentinel cloud: sentinel: transport: #设置Sentinel控制台的主机地址和端口号 dashboard: localhost:9000 # 开启 Sentinel 对 Feign 的支持feign: sentinel: enabled: true |
服务端调用方Controller
|
1
2
3
4
|
@GetMapping("/feignHello")public String feignHello(){ return feignClient.feignHello();} |
服务提供方 FeignClient
|
1
2
3
4
5
6
7
8
9
10
11
|
@FeignClient(contextId = "testFeignClient", value = "注册中心中服务的名称", fallback = FeignFallbackService.class)public interface TestFeignClient { /** * OpenFeign 远程调用的方法 * * @return */ @GetMapping("/test/feignHello") String feignHello();} |
提供一个 FeignClient 接口的实现类,作为限流的处理方法
|
1
2
3
4
5
6
7
|
@Servicepublic class FeignFallbackService implements TestFeignClient{ @Override public String feignHello() { return "Feign 远程调用限流了"; }} |
Sentinel 控制台添加限流规则:
请求方式:http://服务模块注册中心名称/test/feignHello

到此这篇关于Sentinel 之 整合SpringCloud的文章就介绍到这了,更多相关Sentinel 整合SpringCloud内容请搜索米米素材网以前的文章或继续浏览下面的相关文章希望大家以后多多支持米米素材网!
原文链接:https://www.cnblogs.com/Alay/p/15488116.html

发表评论