sentinel集成nacos
sentinel参数会随着业务变动,所以集成nacos非常有必要。
首先要引入三个包
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-extension</artifactId>
</dependency>
<!-- 添加sentinel-datasource-nacos依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
这里我也贴出我的依赖,供大家参考,但是一定要调研引入包是否有冲突。
然后就要做一下几个步骤:
第一步:bootstrap.xml里面配置参数
spring:
cloud:
sentinel:
eager: true
datasource:
flow-rule:
nacos:
# server-addr: nacos-dev.mstpay-inc.com:8848
data-id: mustangpay-promo-center-server-sentinel-flow-rules.json
namespace: ${spring.profiles.active}
group-id: DEFAULT_GROUP
rule-type: flow
data-type: json
注意sentinel里面依赖的nacos配置一定要写到nacos里面,不要写到代码里面
1、要注意安全性
2、修改起来麻烦
mustangpay-promo-center-server-sentinel-flow-rules.json文件里面数据要配置成json
[
{
"resource": "aa",
"limitApp": "default",
"grade": 1,
"count": 2,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
},
{
"resource": "bb",
"limitApp": "default",
"grade": 1,
"count": 2,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
代码里面要引入一个切面
@Configuration
public class SentinelConfig {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
Controller里面要按照下面配置
@PostMapping(value = UrlConstants.MUSTANG_PAY_MERCHANT_ADD_ONE_DRAFT)
@SentinelResource(value = "aa", blockHandler = "handleException", blockHandlerClass = {OnboardingExceptionUtil.class})
public ResponseResult<MerchantSubmitResp> aa(@Validated @RequestBody MerchantSubmitReq req) {
return merchantSubmitRespResponseResult;
}
加一个异常返回类,做一个页面的展示兼容即可。
@Slf4j
public class OnboardingExceptionUtil {
public static ResponseResult<tt> handleException(c req, BlockException ex) {
return ResponseResult.error("Oops! Please try again later.");
}
public static ResponseResult<bb> handleException(b req, BlockException ex) {
return ResponseResult.error("Oops! Please try again later.");
}
public static ResponseResult<cc> handleException(List<a> files, BlockException ex) {
return ResponseResult.error("Oops! Please try again later.");
}
}