springboot集成sentinel的方式,官方文档介绍了两种
一、通过启动命令方式
#项目名称,这个配置的名称会展示在sentinel控制台上
-Dproject.name=test-app
#sentinel地址
-Dcsp.sentinel.dashboard.server=ip:port
#项目在sentinel管理控制台申请的端口,这个如果不配置,sentinel系统会自动分配
-Dserver.port=9090
二、通过配置文件方式
在application.yml中配置
spring:
application:
name: test-app # 项目名称
cloud:
sentinel:
transport:
dashboard: localhost:8080 #sentinel控制台地址
三、第三种配置方式,是因为本人所开发的项目中,打包方式不区分环境,由配置中心根据机器的不同,自动下发配置。启动脚本也不区分环境,项目独特的配置方式和启动脚本,导致不能使用上面两种,又不方便写死在代码或者脚本中。此时只能另辟蹊径。
依然由springboot启动项目,项目启动成功后,手动触发连接控制台。
application类的改造如下:
ConfigurableApplicationContext context=SpringApplication.run(ApiApplication.class, args);
// 连接到控制台,与sentinel控制台通信
System.setProperty("project.name",context.getEnvironment().getProperty("spring.application.name",context.getBean(SentileConfig.class).getProjectName()));
System.setProperty("csp.sentinel.dashboard.server",context.getEnvironment().getProperty("sentinel.dashboard.server",context.getBean(SentileConfig.class).getDashboardServer()));
InitExecutor.doInit();
而在SentileConfig类中,通过@value方式,获取配置文件的内容。
@Configuration
public class SentileConfig {
@Value("${spring.application.name}")
private String projectName ;
@Value("${spring.cloud.sentinel.transport.dashboard}")
private String dashboardServer;
public String getProjectName(){
return projectName;
}
public String getDashboardServer(){
return dashboardServer;
}
}
这种方式也可以实现springboot 集成 sentinel 限流。