博主
258
258
258
258
专辑

第六节 使用注解方式定义资源

亮子 2022-12-27 12:55:54 4234 0 0 0

Sentinel支持通过@SentinelResource注解定义资源并配置blockHandler和fallback函数来进行限流之后的处理。

第一步:引入@SentinelResource注解依赖支持

Sentinel提供了@SentinelResource注解用于定义资源,并提供了AspectJ的扩展用于自动定义资源、处理BlockException等。使用Sentinel Annotation AspectJ Extension的时候需要引入以下依赖:

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

第二步:创建AspectJ配置类

  • Spring Cloud Alibaba

若您是通过Spring Cloud Alibaba接入的Sentinel,则无需额外进行配置即可使用@SentinelResource注解。

  • Spring AOP

若您的应用使用了Spring AOP(无论是Spring Boot还是传统Spring应用),您需要通过配置的方式将SentinelResourceAspect注册为一个Spring Bean:

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

第三步:新建Controller测试方法

package com.shenmazong.hello.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 军哥
 * @version 1.0
 * @description: AntiController
 * @date 2022/12/27 20:20
 */

@RestController
@Slf4j
@RequestMapping(value = "/anti")
public class AntiController {

    /**
     * 注解方式定义资源
     * @SentinelResource value 资源名称
     * @SentinelResource blockHandler 调用被限流/降级/系统保护的时候调用的方法
     * @return
     */
    @SentinelResource(value = "helloWorld3", blockHandler = "blockHandlerForHelloWorld3")
    @RequestMapping(value = "/helloWorld3")
    public String helloWorld3() {
        String msg = "helloWorld3:" + System.currentTimeMillis();
        return msg;
    }

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

第四步:Sentinel控制台新增流控规则

图片alt

第五步:测试

浏览器请求: http://localhost:8080/anti/helloWorld3

  • 正常访问

图片alt

  • 频繁访问

图片alt

  • 控制台异常打印

图片alt