问题描述
在测试sentinel的链路流控模式是失效
spring-cloud-alibaba-dependencies:2.2.13 RELEASE
sentinel-datasource-nacos: 2.2.1
控制层及服务层的代码如下所示:
package com.msb.controller;
import com.msb.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class FlowLimitController {
@Autowired
TestService testService;
@GetMapping("/testA")
public String testA(){
//暂停0.8秒 睡0.8秒
//return "-----testA";
log.info(Thread.currentThread().getName()+":testA");
return testService.common();
}
@GetMapping("/testB")
public String testB(){
return testService.common();
}
}
package com.msb.service;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.stereotype.Service;
//针对来源是限制的服务,而针对链路限制的是api接口
@Service
public class TestService {
// 定义限流资源
@SentinelResource("common")
public String common(){
return "common";
}
}
同时在Sentinel Dashboard上配置流控规则
这样配置完成之后,按照预期的效果,当多次访问/testA路径,服务器将会响应 ex testA,而多次访问/testB路径,服务器依旧响应 testA
解决方法
添加依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-web-servlet</artifactId>
</dependency>
在项目中添加一个FilterContextConfig配置类,自己构建CommonFilter实例
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;
}
}
重新配置链路流控规则
启动微服务,在Sentinel Dashboard中重新配置流控规则
然后你就会发现,你设置的流控规则生效了