给需要流控的微服务引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
去sentinel github官网下载对应版本的控制台jar
https://github.com/alibaba/Sentinel/releases
java -jar启动部署控制台,默认8080端口,默认账户密码都是sentinel
然后修改微服务的配置
spring:
cloud:
sentinel:
transport:
#与sentinel控制台的通信端口
port: 8719
#控制台地址
dashboard: localhost:8080
1.自定义流控响应信息
@Configuration
public class SentinelConfig {
public SentinelConfig(){
WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
@Override
public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
response.setCharacterEncoding("GBK");
response.getWriter().write("流量过大!");
}
});
}
}
2.直接限流,关联限流,链路限流的区别
直接限流就是最普通的限流。
关联限流,假如说有对A接口进行了限流,A关联了B,则B流量大的时候对A限流,B流量不大对A不限。
链路限流,假如说有个服务C,可以通过服务A调服务C,也可以通过服务B调用服务C,这时候对C设置链路A限流,则通过A调C才会限流,B调C不限
3.整合openFeign熔断降级
feign:
sentinel:
enabled: true
4.整合gateway网关流控
给网关服务加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
添加配置
spring:
cloud:
sentinel:
transport:
#与sentinel控制台的通信端口
port: 8888
#控制台地址
dashboard: localhost:8080
5.自定义网关流控响应信息
spring:
cloud:
sentinel:
scg:
fallback:
#响应规则:重定向或者响应
mode: 'response'
#限流成功响应类型
content-type: 'application/json'
#响应体信息
response-body: '网关限流成功'