在用户并发量比较大的情况下,服务会发生雪崩效应:用户同时请求堆积在一个接口,导致其它的接口服务无法访问,这种效果给到用户体验不好。
保护策略:对服务限流(熔断),在高并发场景客户端请求达到阈值,直接调用服务降级方法,给到友好提示如:当前访问人数过多,稍后重试。
Alibaba Sentinel 和Hystrix对比:
图片来源:https://blog.csdn.net/truelove12358/article/details/107507455
Alibaba Sentinel常用有以下三种方式实现服务保护:
- Sentinel dashboard 控制台
- 通过注解
- 自定义编码
本文主要描述Sentinel dashboard来控制限流。
安装Sentinel dashboard下载链接:https://github.com/alibaba/Sentinel/releases
下载成功后,运行:
java -jar sentinel-dashboard-1.8.4.jar
启动成功访问:http://localhost:8080/#/login
账号密码都是:sentinel
SpringCloud整合Sentinelpom.xml
org.springframework.boot spring-boot-starter-webcom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoverycom.alibaba.cloud spring-cloud-starter-alibaba-sentinelorg.springframework.boot spring-boot-starter-parent2.4.2 org.springframework.cloud spring-cloud-dependencies2020.0.5 pom import com.alibaba.cloud spring-cloud-alibaba-dependencies2021.1 pom import
application.yml 配置
server:
port: 8081
spring:
application:
name: sentinel-client
cloud:
# nacos 注册中心
nacos:
discovery:
server-addr: 127.0.0.1:8848
# 服务保护配置
sentinel:
transport:
# dashboard地址
dashboard: localhost:8080
eager: true
启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
启动成功后,访问:http://localhost:8080/#/dashboard
设置限流创建一个Controller,编写接口。
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserCtrl {
@Value("${server.port}")
private String port;
@GetMapping("getUser")
@SentinelResource(value = "getUser", blockHandler = "qpsException")
public String getUser() throws InterruptedException {
Thread.sleep(1000);
return "terry: " + port;
}
public String qpsException(BlockException e) {
e.printStackTrace();
return "当前访问人数过多,稍后重试!";
}
}
在Sentinel dashboard创建流控规则
资源名代码中配置的SentinelResource,QPS阈值1(1秒钟只能有一个用户访问),配置如下:
多次请求后返回结果:



