ITPub博客

Spring 4 + ZooKeeper 配置中心

原创 作者:百联达 时间:2017-04-24 11:15:08 0 删除 编辑
一: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 表达式   注解方式
上一篇: ZooKeeper集群搭建
请登录后发表评论 登录
全部评论

注册时间:2013-02-05

  • 博文量
    260
  • 访问量
    863709