Configuration center for SpringBoot applications

  springboot, zookeeper

SpringBoot application series articles

Order

With the rise of the Internet, the way to improve system performance has gradually changed from vertical scaling to horizontal scaling. It is inevitable that there will be configurations in the cluster, and local configurations are not desirable. Once there are changes, it is very difficult to change one machine after another. It is still necessary to have a centralized configuration center. Once there are configuration changes, the configuration will be automatically distributed to all machines in the cluster. There are many implementations, such as mq triggering changes, such as rpc triggering. Zookeeper belongs to the latter and is often used for cluster election, service discovery and configuration center. This article mainly introduces how to integrate and use zookeeper as the configuration center in SpringBoot.

Prepare zk cluster

Standalone mode can be used, orStand-alone +docker Cluster Construction

Create project

Accessstart.spring.io
图片描述

Properties

server.port=8080

Configure 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

Create zk attribute

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

Use

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

Pit

  • Always connect to localhost:2181 (The configuration of spring cloud needs to be migrated to bootstrap.yml)
  • Zk Changed No Update (To be perfected in the next version)

Resolve zk automatic update

Archaius-zookeeper can be used to automatically update zk configuration, but only if @Value annotation is not supported to obtain variables. However, this method is OK to me, because the variable @Value everywhere makes the variable fly everywhere, which is not easy to manage.

/**
 * 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;
    }
}

Thanks