Spring 4 + ZooKeeper 配置中心

百聯達發表於2017-04-24
一:ZooKeeper 連線配置類


點選(此處)摺疊或開啟

  1. @Configuration
  2. @PropertySource("classpath:context-datasource.properties")
  3. public class ZooKeeperElConfig {

  4.     @Value("${zookeeper.cluster.url}")
  5.     private String zooKeeperClusterUrl;

  6.     @Value("${zookeeper.root.path}")
  7.     private String zooKeeperRootPath;

  8.     @Autowired
  9.     private Environment environment;

  10.     @Bean
  11.     public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
  12.         return new PropertySourcesPlaceholderConfigurer();
  13.     }

  14.     @Bean(name = "zkClient")
  15.     public CuratorFramework zkClient() {
  16.         CuratorFramework client = CuratorFrameworkFactory.builder().connectString(zooKeeperClusterUrl)
  17.                 .sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(1000, 3)).namespace(zooKeeperRootPath).build();
  18.         client.start();
  19.         return client;
  20.     }
  21.     
  22.     
  23.     
  24. }

二: 讀取ZooKeeper引數工具類


點選(此處)摺疊或開啟

  1. @Component("systemElConfig")
  2. public class SystemElConfig {

  3.     @Autowired
  4.     CuratorFramework zkClient;

  5.     public String getProperty(String propertyName) {
  6.         String property = "";
  7.         try {
  8.             property = new String(zkClient.getData().forPath("/" + propertyName));
  9.         }
  10.         catch (Exception e) {
  11.             e.printStackTrace();
  12.         }

  13.         return property;
  14.     }

  15. }
三: 其它配置類引用ZooKeeper中的引數資訊舉例


點選(此處)摺疊或開啟

  1. @Value("#{systemElConfig.getProperty('mailHost')}")
  2.     private String mailHost;
採用Spring EL 表示式   註解方式

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28624388/viewspace-2137860/,如需轉載,請註明出處,否則將追究法律責任。

相關文章