Sentinel接口限流框架在Springcloud中的简单应用

10 篇文章 0 订阅
5 篇文章 0 订阅

Springboot使用Sentinel,还是稍显复杂。alibaba封装了针对Springcloud的使用,更加简单。

还是上次启动的那个控制台。

一、创建Springboot工程

二、添加Pom依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    <version>2021.1</version>
</dependency>

三、修改yml配置文件

server:
    port: 8080
spring:
    application:
        name: springcloud-sentinel-demo-20210531
    cloud:
        sentinel:
            transport:
                dashboard: localhost:8756

在Springboot的整合中需要在JVM添加参数,Springcloud只需要在yml添加配置即可。

四、创建限流处理类

package com.chris.sentinel;

import com.alibaba.csp.sentinel.slots.block.BlockException;

/**
 * @author Chris Chan
 * Create on 2021/5/31 14:54
 * Use for:
 * Explain: 限流处理器
 */
public class TestBlockHandlerManager {
    public static String testBlockHandler(BlockException e) {
        return "The system is busy. Please try again later.";
    }
}

和上次是一样的。把限流处理方法跟接口放一起是不合适的,尤其是当很多方法的处理方式都不一样的时候,最好还是用一个类专门管理起来。保证类的功能单一。

五、创建测试接口

package com.chris.sentinel;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Chris Chan
 * Create on 2021/5/31 14:52
 * Use for:
 * Explain:
 */
@RestController
@RequestMapping("api/test")
public class TestController {
    @SentinelResource(value = "test", blockHandlerClass = TestBlockHandlerManager.class, blockHandler = "testBlockHandler")
    @GetMapping("test")
    public String test() {
        return "Called api/test/test success.";
    }
}

六、启动程序

七、在控制台添加一个流控规则,设置每秒访问超过两次即被限流。

八、反复刷新调用test接口

当刷新缓慢时,返回正常。

当快速刷新时,返回系统繁忙。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值