1、添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-web-servlet</artifactId>
</dependency>
2、下载sentinel dashboard
首先,查看spring-cloud-starter-alibaba-sentinel依赖添加的sentinel-core的版本号
可以看到sentinel-core的版本号是1.7.1,所以 sentinel dashboard的版本号也要是1.7.1,所以本案例下载 1.7.1的dashboard
下载地址:
https://github.com/alibaba/Sentinel/releases
下载下来的jar包是: sentinel-dashboard-1.7.1.jar
使用java -jar sentinel-dashboard-1.7.1.jar 启动dashboard
java -jar sentinel-dashboard-1.7.1.jar
3、添加配置
添加spring.cloud.sentinel.transport.dashboard 和management.endpoints.web.exposure.include配置,如下:
spring:
application:
name: say
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: b62b1132-d8c6-4740-b745-75bcfb4f66a5
cluster-name: GD
sentinel:
transport:
dashboard: localhost:8080
logging:
config: classpath:log4j2.xml
server:
port: 8091
feign:
client:
config:
helloworld:
loggerLevel: full
management:
endpoints:
web:
exposure:
include: '*'
4、添加FilterContextConfig 配置,如果不添加 链路流控模式会不生效
package com.codex.terry.configuration;
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterContextConfig {
/**
* @NOTE 在spring-cloud-alibaba v2.1.1.RELEASE及前,sentinel1.7.0及后,关闭URL PATH聚合需要通过该方式,spring-cloud-alibaba v2.1.1.RELEASE后,可以通过配置关闭:spring.cloud.sentinel.web-context-unify=false
* 手动注入Sentinel的过滤器,关闭Sentinel注入CommonFilter实例,修改配置文件中的 spring.cloud.sentinel.filter.enabled=false
* 入口资源聚合问题:https://github.com/alibaba/Sentinel/issues/1024 或 https://github.com/alibaba/Sentinel/issues/1213
* 入口资源聚合问题解决:https://github.com/alibaba/Sentinel/pull/1111
*/
@Bean
public FilterRegistrationBean sentinelFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new CommonFilter());
registration.addUrlPatterns("/*");
// 入口资源关闭聚合
registration.addInitParameter(CommonFilter.WEB_CONTEXT_UNIFY, "false");
registration.setName("sentinelFilter");
registration.setOrder(1);
return registration;
}
}
5、打开 sentinel dashboard进行流控、降级等配置
http://localhost:8080/