项目采用了txlcn作为分布式事务处理组件,但具体调用请求的时候,发现分布式事务并没有生效。跟踪了源码,发现txlcn的实现是通过在调用请求的时候附加请求头(X-Group-ID)给参与方来实现的,然后请求方的groupId和参与方的groupId并不一样,深入源码,发现是在SpringTracingApplier类里进行了请求头的提取。
public class SpringTracingApplier implements com.codingapi.txlcn.tracing.http.spring.HandlerInterceptor, WebMvcConfigurer
可以看出,这个类是个拦截器,然后调试的时候并没有发现这个拦截器,也就是说本拦截器未被注册上去
由于本类同时实现了WebMvcConfigurer接口,用于注册拦截器,也就是说实现的这个接口未生效
看了该类的注释,是通过@EnableWebMvc来启用的
Defines callback methods to customize the Java-based configuration for Spring MVC enabled via @EnableWebMvc
再看EnableWebMvc的注释:
Note: only one @Configuration class may have the @EnableWebMvc annotation to import the Spring Web MVC configuration. There can however be multiple @Configuration classes implementing WebMvcConfigurer in order to customize the provided configuration.
If WebMvcConfigurer does not expose some more advanced setting that needs to be configured consider removing the @EnableWebMvc annotation and extending directly from WebMvcConfigurationSupport or DelegatingWebMvcConfiguration
可以看出可以有多个类实现WebMvcConfigurer 接口,并通过@EnableWebMvc启用。如果没有暴露其他更高级的设置,可以考虑继承WebMvcConfigurationSupport 类
找了下项目的代码,WebConfig就是直接继承了WebMvcConfigurationSupport 类,修改了这个类,添加@EnableWebMvc注解,实现WebMvcConfigurer接口,再次启动,问题解决
@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer{ }