Apollo(四)-Java环境调用参数-代码例子

x33g5p2x  于2021-12-20 转载在 其他  
字(6.7k)|赞(0)|评价(0)|浏览(337)

说明

下面以github下载的源码中SimpleApolloConfigDemo为例

前提

1.启动apollo的apollo-configservice、apollo-adminservice、apollo-portal服务(具体见Apollo(二)),或者已部署到环境的则在环境启动相应的程序;

读参数

代码

SimpleApolloConfigDemo.java、app.properties、application.yml、log4j2.xml、spring.xml拷贝到自己的工程,若包名改变,相应配置文件要改过来;具体工程目录和代码如下所示:

pom.xml
<properties>
        <spring.version>5.1.7.RELEASE</spring.version>
        <spring-boot.version>2.0.5.RELEASE</spring-boot.version>
        <spring-cloud.version>Finchley.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.ctrip.framework.apollo</groupId>
            <artifactId>apollo-client</artifactId>
            <!--
            <version>0.7.2</version>
            -->
            <version>1.4.0</version>
        </dependency>
        <!-- for spring demo -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- for spring boot demo -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>${spring-boot.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <!-- for refresh scope demo -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-context</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!-- take over jcl -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>
SimpleApolloConfigDemo.java
package com.ydfind.apollo;

import com.google.common.base.Charsets;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Jason Song(song_s@ctrip.com)
 */
public class SimpleApolloConfigDemo {
    private static final Logger logger = LoggerFactory.getLogger(SimpleApolloConfigDemo.class);
    private String DEFAULT_VALUE = "undefined";
    private Config config;

    public SimpleApolloConfigDemo() {
        ConfigChangeListener changeListener = new ConfigChangeListener() {
            @Override
            public void onChange(ConfigChangeEvent changeEvent) {
                logger.info("Changes for namespace {}", changeEvent.getNamespace());
                for (String key : changeEvent.changedKeys()) {
                    ConfigChange change = changeEvent.getChange(key);
                    logger.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
                            change.getPropertyName(), change.getOldValue(), change.getNewValue(),
                            change.getChangeType());
                }
            }
        };
        config = ConfigService.getAppConfig();
        config.addChangeListener(changeListener);
    }

    private String getConfig(String key) {
        String result = config.getProperty(key, DEFAULT_VALUE);
        logger.info(String.format("Loading key : %s with value: %s", key, result));
        return result;
    }

    public static void main(String[] args) throws IOException {
        SimpleApolloConfigDemo apolloConfigDemo = new SimpleApolloConfigDemo();
        System.out.println(
                "Apollo Config Demo. Please input key to get the value. Input quit to exit.");
        while (true) {
            System.out.print("> ");
            String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine();
            if (input == null || input.length() == 0) {
                continue;
            }
            input = input.trim();
            if (input.equalsIgnoreCase("quit")) {
                System.exit(0);
            }
            apolloConfigDemo.getConfig(input);
        }
    }
}
app.properties
apollo:
  bootstrap:
    enabled: true
    # will inject 'application' and 'TEST1.apollo' namespaces in bootstrap phase
    namespaces: application,TEST1.apollo,application.yaml
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration monitorInterval="60">
  <appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="[apollo-demo][%t]%d %-5p [%c] %m%n"/>
    </Console>
    <Async name="Async" includeLocation="true">
      <AppenderRef ref="Console"/>
    </Async>
  </appenders>
  <loggers>
    <logger name="com.ydfind.apollo" additivity="false" level="DEBUG">
      <AppenderRef ref="Async"/>
    </logger>
    <root level="INFO">
      <AppenderRef ref="Async"/>
    </root>
  </loggers>
</configuration>
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:apollo="http://www.ctrip.com/schema/apollo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
    <apollo:config order="10"/>
    <apollo:config namespaces="TEST1.apollo,application.yaml" order="11"/>

    <bean class="com.ctrip.framework.apollo.demo.spring.xmlConfigDemo.bean.XmlBean">
        <property name="timeout" value="${timeout:200}"/>
        <property name="batch" value="${batch:100}"/>
    </bean>

    <context:annotation-config />
</beans>

运行

运行SimpleApolloConfigDemo.java的main函数,如下所示,能正确独处timeout的值为1000.

参数修改时onChange事件

添加启动参数:-Denv=dev -Ddev_meta=http://localhost:8080

重新编译后再运行程序,然后修改timeout的值,可以看到程序是可以拦截变化的

相关文章