个人博客:http://59.110.230.15欢迎捧场!
在当前spring cloud体系下依赖SDK阶段实现的分布式微服务中,通常会把一些架构级的功能提到一个单独的包来开发。然后打包SDK供其他微服务依赖使用。
接触到一些项目和网上一些文章写的starter的autoConfiguration都是使用的@configuration注解进行注入的。
如果使用@configuration或者@component组件直接注入,就会导致所有服务强依赖问题。比如SDK中有两个功能:
这里不讨论分包的问题哈。假设就放在了一个SDK下。这时候A服务需要redis做分布式锁。B服务并不需要redis分布式锁,但是也需要集成druid数据源。那么如果想用SDK的话,就强制引入了redis。
而且这里还要求了微服务的包名前缀和SDK的包前缀需要一致,不一致时还要在main启动上加入scanBackage。否则扫描不到。
下面介绍一下我写的starter模式的开发,核心思想时根据yml中的配置项来决定加载哪些类注入到spring容器中。从而对SDK中的功能做自定义加载使用无需强依赖。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.wm.tools.spring.boot.trace.TraceAutoConfiguration
这里配置的是spring的autocinfiguration机制所加载的类
@EnableConfigurationProperties(TraceProperties.class)
@ConditionalOnProperty(prefix = "wm.trace", name = "enable", havingValue = "true", matchIfMissing = true)
public class TraceAutoConfiguration {
@Bean
public FilterRegistrationBean contextFilterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new HttpTraceFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("httpTraceFilter");
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registrationBean;
}
}
这里关键使用了两个注解:
这里我的功能室当wm.trace.enable!=false时就加载这个webFilter。这里也可以使用@bean注入切面等其他原来想用@component的组件,例如:
@EnableConfigurationProperties({IdempotentProperties.class})
@ConditionalOnProperty(prefix = "codingfly.idempotent", name = "enable", havingValue = "true", matchIfMissing = true)
public class IdempotentAutoConfiguration {
private final IdempotentProperties idempotentProperties;
@Bean
public IdempotentAspect idempotentAspect() {
return new IdempotentAspect(stringRedisTemplate, idempotentStrategyContext, idempotentScopeContext, idempotentProperties);
}
}
这是我领做的一个功能,开启幂等切面。
这时候我们的这个切面或者过滤器是不需要使用@webFilter或者@Component注入的。
这里被注入的@bean该怎么开发就怎么开发就好了。
各个微服务引入SDK后,通过在yml中配置:
wm:
trace:
enable: true/false
就可以控制容器的加载了。做到按需加载。而且不用配置scanBackage了。