如何使用 zookeeper 作为基于 spring 的 Web 应用程序的数据源加载属性?

How to load properties using zookeeper as the data source for a spring based web application?

我有一个使用 spring 初始化并使用 maven 构建的 Web 应用程序。 使用静态存在的属性文件加载各种属性。由于不同的环境需要相同属性的不同值,因此我使用 Maven 配置文件根据构建时的环境加载不同的属性文件。 例如:- dev.properties 用于开发环境,prod.properties 用于生产环境。

现在我想让构建独立于属性文件, 属性的值将在上下文初始化期间从某些数据源(zookeeper)中获取。

如何在上下文初始化前加载属性?

Properties 只是 Java class 之一,Apache 配置项目恰好提供了这样的抽象。我刚刚向您展示了 JDBC 的示例,但那里确实有很多其他内容。这是我如何从 DB StoredProcedure 加载属性的示例:

<jee:jndi-lookup id="dataSource" jndi-name="DS"/>

<bean id="storedProcedureConfiguration" class="com.my.proj.config.StoredProcedureConfiguration"
      p:dataSource-ref="dataSource"
      p:sqlQuery="pki_props.getProperties"/>


<bean id="propertiesFromDB" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
      p:staticMethod="org.apache.commons.configuration.ConfigurationConverter.getProperties"
      p:arguments-ref="storedProcedureConfiguration"/>

<context:property-placeholder properties-ref="propertiesFromDB"/>

因此,您可以实现自己的 AbstractConfiguration 从 Zookeeper 加载 Properties 并将其注入 <context:property-placeholder>

在 java 构造函数中,只需设置与 Zookeeper 服务器的连接并使用 Zookeeper 客户端方法获取所需数据。您可以在此处找到示例:http://zookeeper.apache.org/doc/trunk/javaExample.html

它看起来像这样(但你必须详细说明)

public YourConstructor() {
Zookeeper zk = new ZooKeeper(host,...);
zk.getData(...);
}

Spring Cloud Config Zookeeper offers a way to do that. I posted a brief example of use here