Sentinel在提供方对请求的限流降级处理
添加maven依赖
<!--引入sentinel 熔断 降级 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
在项目的application.yml中添加如下配置信息:
#配置sentinel
spring:
sentinel:
transport:
dashboard: localhost:8883
#控制台的port
port: 8719
下载sentinel安装到本地
https://github.com/alibaba/spring-cloud-alibaba/wiki/Sentinel
我这里安装的版本是 sentinel.dashboard-1.6.3.jar
在sentinel.dashboard-1.6.3.jar
所在的目录下面打开cmd执行命令:
java -jar sentinel.dashboard-1.6.3.jar --server.port=8883
浏览器打开页面;
输入登录的用户名:sentinel
密码:sentinel
随便请求项目的一个路径,就会在dashboard面板中出现如下信息。
每一个微服务都引入统计审计信息spring-boot-starter-actuator
每一个微服务都引入统计审计信息spring-boot-starter-actuator
Endpoint 支持
在使用 Endpoint 特性之前需要在 Maven 中添加 spring-boot-starter-actuator 依赖,并在配置中允许 Endpoints 的访问。
Spring Boot 1.x 中添加配置 management.security.enabled=false。暴露的 endpoint 路径为 /sentinel
Spring Boot 2.x 中添加配置 management.endpoints.web.exposure.include=*。暴露的 endpoint 路径为 /actuator/sentinel
Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
提供方做降级处理
添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
在配置文件中添加配置信息
management.endpoints.web.exposure.include=*
添加自定义流控响应配置类
**
* @date 2021-02-22 2:19 下午
* @description sentinel自定义返回方法
*/
@Configuration
public class MySeckillSentinelConfig {
public MySeckillSentinelConfig() {
WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
@Override
public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
//请求流量过大就返回
R r = R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMsg());
//解决response乱码
response.setCharacterEncoding("utf-8");
response.setContentType("application/json");
response.getWriter().write(JSON.toJSONString(r));
}
});
}
}
当请求流量过大的时候就会触发