sentinel注解方式限流

1、新建一个springWeb项目

2、引入sentinel核心依赖、sentinel-annotation-aspectj,因为Sentinel中使用AspectJ的扩展用于定义资源、处理BlockException等,所以要在项目中引入sentinel-annotation-aspectj依赖

<!--sentinel核心依赖-->
<dependency>
      <groupId>com.alibaba.csp</groupId>
      <artifactId>sentinel-core</artifactId>
      <version>1.7.2</version>
</dependency>

<dependency>
      <groupId>com.alibaba.csp</groupId>
      <artifactId>sentinel-annotation-aspectj</artifactId>
      <version>1.7.2</version>
</dependency>

3、创建AspectJ配置类,主要是为了得到SentinelResourceAspect对象

@Configuration
public class SentinelAspectConfiguration {
    @Bean
    public SentinelResourceAspect sentinelResourceAspect(){
        return new SentinelResourceAspect();
    }
}

4、创建一个controller,实现限流控制;

@SentinelResource注解用来标识资源是否被限流、降级。其中value的值表示的是资源名,blockHandler表示限流的具体回调方法

@RestController
public class TestAnnController {

    //定义限流资源和限流降级回掉函数
    @GetMapping("ann")
    @SentinelResource(value = "Sentinel_Ann", blockHandler = "exceptionHandler")
    public String hello() {

        return "Hello Sentinel";
    }

    //blockHandler函数,原方法被限流/降级/系统保护的时候调用
    public String exceptionHandler(BlockException ex) {
        ex.printStackTrace();
        return "系统繁忙,请稍后";
    }
}

5、引入本地应用接入sentinel本地控制台的依赖

<!--本地应用接入sentinel本地控制台的依赖-->
<dependency>
     <groupId>com.alibaba.csp</groupId>
     <artifactId>sentinel-transport-simple-http</artifactId>
     <version>1.7.2</version>
</dependency>

6、在yml文件中配置本地sentinel限流控制台;

spring:
  application:
    name: SentinelAnno
  cloud:
    sentinel:
      transport:
        dashboard: localhost:9000

7、配置流控规则,其中资源名就是@SentinelResource中value的值,限流之后的处理便是blockHandler的值

 最终的效果

  

猜你喜欢

转载自blog.csdn.net/weixin_38829588/article/details/123613423