SpringBoot应用之配置中心

SpringBoot应用系列文章

随着互联网的兴起,提高系统性能的方式,渐渐从垂直伸缩的方式变为水平伸缩。集群中不可避免地会有配置,本地配置就不可取了,一旦有改动就得一台台机器去改动,很是费劲。有个集中配置中心仍是很是有必要的,一旦有配置改动,自动下发配置到集群的各个机器中。其中的实现方式有许多,好比经过mq触发变动,好比经过rpc方式触发。zookeeper就属于后者,常常用来作集群选举,服务发现,配置中心。本文主要介绍了如何在SpringBoot中集成和使用zookeeper做为配置中心。java

准备zk集群

可使用standalone模式,或者单机+docker构建集群git

建立工程

访问start.spring.io
图片描述github

配置application.properties

server.port=8080

配置bootstrap.yml

spring:
  application:
    name: demoapp
  cloud:
    zookeeper:
        enabled: true
        connectString: 192.168.99.100:2181,192.168.99.100:2182,192.168.99.100:2183
    config:
      # TODO: refactor spring-cloud-config to use refresh, etc.. with out config client
      enabled: false

建立zk属性

zkCli.sh
create /config ""
create /config/demoapp ""
create /config/demoapp/msg helloworld
quit

使用

@Value("${msg:defaultMsg}")
String msg

  • 老是链接到localhost:2181(须要把spring cloud的配置迁移到bootstrap.yml)
  • zk变化了没有更新(有待下一个版本完善)

解决zk自动更新

能够采用archaius-zookeeper来实现zk配置的自动更新,不过前提是不支持使用@Value注解来获取变量。不过这种方式对我来讲是OK的,由于随处@Value变量使得变量随处飞,很差管理。spring

/**
 * https://github.com/Netflix/archaius/wiki/ZooKeeper-Dynamic-Configuration
 */
@Component
public class ArchaiusZkConfig {

    @Autowired
    CuratorFramework client;

    @Value("${spring.application.name}")
    String appName;

    @PostConstruct
    public void installZkConfig() throws Exception {
        String zkConfigRootPath = "/config/"+appName;
        ZooKeeperConfigurationSource zkConfigSource = new ZooKeeperConfigurationSource(client, zkConfigRootPath);
        zkConfigSource.start();
        DynamicWatchedConfiguration zkDynamicConfig = new DynamicWatchedConfiguration(zkConfigSource);
        ConfigurationManager.install(zkDynamicConfig);
    }

    public String getDynamicUpdate(){
        String myProperty = DynamicPropertyFactory.getInstance()
                .getStringProperty("msg", "<none>")
                .get();
        return myProperty;
    }
}

鸣谢

相关文章
相关标签/搜索