系列文章:
【Sentinel入门】01 最简单的例子 helloworld
【Sentinel入门】02 @SentinelResource语法(blockHandler、fallback)
【Sentinel入门】03 规则类型(BlockException、FlowException、ParamFlowException、DegradeException)
【Sentinel入门】04 springmvc 集成Sentinel & 全局异常处理类统一处理异常(BlockExceptionHandler接口)
【Sentinel入门】05 springmvc 集成Sentinel & springboot集成Sentinel & 链路模式失效 & WebContextUnify & CommonFilter
前言
本篇接【Sentinel入门】04 springmvc 集成Sentinel & 全局异常处理类统一处理异常(BlockExceptionHandler接口),其中有下面的代码:
config.setWebContextUnify(true);
这段代码作用是什么?
webContextUnify属性
按照源码中的注释:
自从 sentinel-spring-webmvc-adapter -1.7.2
开始,在SentinelWebMvcConfig
对象(sentinel参数配置类)中含有一个webContextUnify属性,默认值为true,表示合并web context,达到节约内存的目的;如果设置为false,表示入口处的contexts会拆分为不同的url。我们针对链路模式,必须设置为false,否则会导致链路模式不生效
完整文件:
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
//重写父类方法
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Add Sentinel interceptor
addSpringMvcInterceptor(registry);
}
private void addSpringMvcInterceptor(InterceptorRegistry registry) {
SentinelWebMvcConfig config = new SentinelWebMvcConfig();
// Depending on your situation, you can choose to process the BlockException via
// the BlockExceptionHandler or throw it directly, then handle it
// in Spring web global exception handler.
// config.setBlockExceptionHandler((request, response, e) -> { throw e; });
// Use the default handler.
config.setBlockExceptionHandler(new DefaultBlockExceptionHandler());
// Custom configuration if necessary
config.setHttpMethodSpecify(true);
// By default web context is true, means that unify web context(i.e. use the default context name),
// in most scenarios that's enough, and it could reduce the memory footprint.
// If set it to false, entrance contexts will be separated by different URLs,
// which is useful to support "chain" relation flow strategy.
// We can change it and view different result in `Resource Chain` menu of dashboard.
config.setWebContextUnify(true);
config.setOriginParser(request -> request.getHeader("S-user"));
// 注册一个 sentinel interceptor(拦截器)
registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**");
}
http://127.0.0.1:8088/hello
从上图对比可以看出:流控模式为链路模式时,sentinel 1.7.2以后版本,Sentinel Web过滤器默认会聚合所有URL的入口为sentinel_spring_web_context
,因此单独对指定链路限流会不生效
老版本下的alibaba集成sentinel下的webContextUnify
在早期版本中,alibaba集成sentinel时,需要额外引入sentinel-web-servlet-1.8.0.jar ,内置 CommonFilter类,内含:
public static final String WEB_CONTEXT_UNIFY = "WEB_CONTEXT_UNIFY";
也是起到相同作用,至于详细原理和注意事项,待后续详解