`
15606915740
  • 浏览: 18479 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
文章分类
社区版块
存档分类
最新评论

springboot集成disconf

阅读更多
import com.baidu.disconf.client.DisconfMgrBean;
import com.baidu.disconf.client.DisconfMgrBeanSecond;
import com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

配置类模板
public abstract class DisConfigTemplate {

    @Bean(destroyMethod = "destroy")
    public DisconfMgrBean getDisconfMgrBean(){
        DisconfMgrBean dmb = new DisconfMgrBean();
        dmb.setScanPackage(getScanPackage());
        return dmb;
    }

    public abstract String getScanPackage();

    @Bean(destroyMethod = "destroy",initMethod = "init")
    public DisconfMgrBeanSecond getDisconfMgrBean2(){
        return new DisconfMgrBeanSecond();
    }

    @Bean(name = "reloadablePropertiesFactoryBean")
    @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
    public ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean() {
        ReloadablePropertiesFactoryBean propertiesFactoryBean = new ReloadablePropertiesFactoryBean();
        propertiesFactoryBean.setSingleton(true);
        propertiesFactoryBean.setLocations(getFiles());
        return propertiesFactoryBean;
    }

    public abstract List<String> getFiles();

    @Bean(name = "propertyPlaceholderConfigurer")
    public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean){
        PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
        placeholderConfigurer.setIgnoreResourceNotFound(true);
        placeholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
        try {
            Properties properties = reloadablePropertiesFactoryBean.getObject();
            placeholderConfigurer.setProperties(properties);
        } catch (IOException e) {
            throw new RuntimeException("unable to find properties", e);
        }
        return placeholderConfigurer;
    }
}

配置类
@Configuration
public class DisconfConfig extends DisConfigTemplate{

     @Override
     public List<String> getFiles() {
        List<String> fileNames = Arrays.asList("classpath:edge-common.properties");
        return fileNames;
     }

     @Override
     public String getScanPackage() {
        return "com.clife.gatewaybg";
     }
}

获取spring的环境变量类
@Component
public class SpringContextUtil implements ApplicationContextAware{
    private static ApplicationContext applicationContext; // Spring应用上下文环境

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T>  T getBean(String name) throws BeansException
    {
        return (T) applicationContext.getBean(name);
    }
}

重新加载变量到内存的类
@Component
@Scope("singleton")
@DisconfFile(filename = ScheDisconfUpdate.PROPERTIES_FILE)
@DisconfUpdateService(classes = { ScheDisconfUpdate.class })
public class ScheDisconfUpdate implements IDisconfUpdate
{
    protected final static String PROPERTIES_FILE = "common.properties";        // 配置文件名
    Logger logger = LoggerFactory.getLogger(ScheDisconfUpdate.class);

    @Autowired
    private SpringContextUtil springContextUtil;    // ApplicationContext


    @Override
    public void reload() throws Exception
    {
        String a = null;
        logger.info("重新加载disconf配置文件开始>>>>>>>>");
        Map disconfPropertiesRelMap = new HashMap();
        disconfPropertiesRelMap.put("test.test.test", "test");
        // continue add properties...

        resetPropertiesValues("com.controller.TestController", disconfPropertiesRelMap);
        logger.info("重新加载disconf配置文件结束>>>>>>>>");
    }


    @SuppressWarnings(
            { "unchecked", "rawtypes", "static-access" })
    private void resetPropertiesValues(String reflactSetPropClassName, Map disconfPropertiesRelMap)
    {
        if (!CollectionUtils.isEmpty(disconfPropertiesRelMap))
        {
            Set<Object> sets = disconfPropertiesRelMap.keySet();
            for(Object disconfkey : sets){
                Object propertiesKey = disconfPropertiesRelMap.get(disconfkey);
                if (!StringUtils.isEmpty((String)disconfkey))
                {
                    try
                    {
                        String afterChangedValue = getPropertiesValueByKay((String) disconfkey);
                        logger.info("disconf通过key:{}获取value:{}", disconfkey, afterChangedValue);
                        if (afterChangedValue != null)
                        {
                            Class involkPropertiesClass = Class.forName(reflactSetPropClassName);
                            String methodName = "set" + ((String) propertiesKey).substring(0, 1).toUpperCase() + ((String) propertiesKey).substring(1);
                            logger.info("disconf反射调用方法:{}", methodName);
                            Method method = involkPropertiesClass.getMethod(methodName, String.class);
                            method.invoke(springContextUtil.getApplicationContext().getBean(TestController.class), afterChangedValue);
                            logger.info("disconf修改重新修改属性:{}的值:{}", disconfkey, afterChangedValue);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.error("disconf修改key值更新失败!e:{}", disconfkey, e.getMessage());
                    }
                }
            }
        }
    }


    private String getPropertiesValueByKay(String key)
    {
        try
        {
            Map map = FileTypeProcessorUtils.getKvMap(SupportFileTypeEnum.PROPERTIES, PROPERTIES_FILE);
            return map.get(key) == null ? null : map.get(key).toString();
        }
        catch (Exception e)
        {
            logger.error("disconf修改通过key:{}获取value失败!e:{}", key, e.getMessage());
            return null;
        }
    }
}


测试类
@RestController
public class TestController {

    @Value("${test.test.test}")
    private String test;
    @GetMapping(value = "/1/2")
    public String gettest(){
        return test+":woo";
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics