Sentinel 整合SpringCloud Sentinel 整合SpringCloud的详细教程

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Sentinel 整合SpringCloud Sentinel 整合SpringCloud的详细教程

Vermeer   2021-10-31 我要评论
想了解Sentinel 整合SpringCloud的详细教程的相关内容吗,Vermeer在本文为您仔细讲解Sentinel 整合SpringCloud的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Sentinel,整合SpringCloud,Sentinel,SpringCloud,下面大家一起来学习吧。

Spring Cloud Alibaba Sentinel 是阿里巴巴提供的,致力于提供微服务一站式解决方案,Spring Cloud Alibaba 默认为 Sentinel 整合了,ServeLet、RestTemplate、FeignClient 和 Spring Flux。在 Spring 的生态中不仅不全了 Hystrix 在 ServeLet 和 RestTemplate 这一块的空白,而且还完美的兼容了 Hystrix 在 Feign 中的限流降级用法,并支持运行时灵活的配置和调整限流降级规则。

引入依赖:

<!--Sentinel 整合SpringCloud 的依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel</artifactId>
    <version>2.2.0.RELEASE</version>
</dependency>

配置文件:

(入门使用中,应用名称使用的 JVM 参数设置的,整合 SpringCloud 就不需要那样了,配置文件中配置了应用的名称后,Sentinel 会自动加载)

# 设置应用的名称
spring:
  application:
    name: springCloudSentinel
  cloud:
    sentinel:
      transport:
 
        #设置Sentinel控制台的主机地址和端口号
        dashboard: localhost:9000

编写测试 Controller ,控制台添加 Sentinel_Cloud 资源 限流测试

@SentinelResource(value = "Sentinel_Cloud",blockHandler = "exceptionHandler")
@GetMapping("/sentinelCloud")
public String sentinelCloud(){
    //使用限流规则
    return "Sentinel_Cloud,成功调用";
}

限流时调用的方法:

/**
 * 定义降级 / 限流 的处理函数
 *
 * @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自动化配置类生效。

# 设置应用的名称
spring:
  application:
    name: springCloudSentinel
  cloud:
    sentinel:
      transport:
 
        #设置Sentinel控制台的主机地址和端口号
        dashboard: localhost:9000
 
# 开启 Sentinel 对 Feign 的支持
feign:
  sentinel:
    enabled: true

服务端调用方Controller

@GetMapping("/feignHello")
public String feignHello(){
    return feignClient.feignHello();
}

服务提供方 FeignClient

@FeignClient(contextId = "testFeignClient", value = "注册中心中服务的名称", fallback = FeignFallbackService.class)
public interface TestFeignClient {
 
   /**
    * OpenFeign 远程调用的方法
    *
    * @return
    */
   @GetMapping("/test/feignHello")
   String feignHello();
}

提供一个 FeignClient 接口的实现类,作为限流的处理方法

@Service
public class FeignFallbackService  implements TestFeignClient{
   @Override
   public String feignHello() {
      return "Feign 远程调用限流了";
   }
}

Sentinel 控制台添加限流规则:

请求方式:http://服务模块注册中心名称/test/feignHello

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们