SpringBoot应用之配置中心

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

准备zk集群

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

创建工程

访问start.spring.io

配置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变量使得变量随处飞,不好管理。

/**
 * https://github.com/Netflix/archaius/wiki/ZooKeeper-Dynamic-Configuration
 * Created by patterncat on 2016-01-24.
 */
@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;
    }
}

本工程的源码见configdemo

鸣谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值