美文网首页
springboot+dubbo微服务使用策略模式的坑

springboot+dubbo微服务使用策略模式的坑

作者: 风一样的存在 | 来源:发表于2020-11-18 23:47 被阅读0次

    由于要实现一个功能,但是很多模块都是要实现同一个功能,不同的人开发不同的模块,最后出现了if-else,switch-case的语句,我瞬间炸了。我把共同实现的功能写了个接口,然后使用策略模式。但是出现个问题:每个service都是dubbo的服务,通过@Reference注入进来,但是依赖的服务必须在消费的服务前启动,换言之必须消费者在提供者之后启动,不然会报错。因为这个时候spring容器里面还实例化不了那个bean。

    @Component
    public class ManualSyncClient implements InitializingBean {
        @Autowired
        private ApplicationContextHelper applicationContextHelper;
    
        private Map<String, ManualSyncService> handlers = new ConcurrentHashMap();
    
        @Override
        public void afterPropertiesSet() throws Exception {
            Map<String, ManualSyncService> statementHandles = applicationContextHelper.getBeansOfType(ManualSyncService.class);
            for (Map.Entry<String, ManualSyncService> entry : statementHandles.entrySet()) {
                handlers.put(entry.getValue().getTableName(), entry.getValue());
            }
        }
    
        public void manualSync(String tag, Date startDate, Date endDate, Long regionId) {
            handlers.get(tag).manualSyncReportData(startDate,endDate,regionId);
        }
    }
    
    
    /**
     * 获取spring容器的bean
     * @author jack
     */
    @Component
    public class ApplicationContextHelper implements ApplicationContextAware {
        private ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    
        public <T> T getBean(Class<T> clazz) {
            return applicationContext.getBean(clazz);
        }
        public <T> Map<String, T> getBeansOfType(Class<T> clazz) {
            return applicationContext.getBeansOfType(clazz);
        }
    }
    

    最后只能规避这个问题:不实现InitializingBean接口了,在使用的时候再去spring容器里获取。

    参考:InitializingBean和SmartInitializingSingleton

    相关文章

      网友评论

          本文标题:springboot+dubbo微服务使用策略模式的坑

          本文链接:https://www.haomeiwen.com/subject/cmnhiktx.html