flink整合apollo动态监听获取配置

获取apollo动态配置demo

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.wlyuan.flink.listener.ApolloConfigListener;
import com.wlyuan.flink.utils.PropertiesUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * flink整合apollo
 * @author songmin
 * @date 2022/7/14 15:17
 */
public class FlinkIntegrateApolloDemo {

    private static final Logger logger = LoggerFactory.getLogger(FlinkIntegrateApolloDemo.class);

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.addSource(new RichSourceFunction<String>() {
            private Config config;

            @Override
            public void open(Configuration parameters) throws Exception {
                String namespace = PropertiesUtil.getString("apollo.namespace");
                config = ConfigService.getConfig(namespace);
                config.addChangeListener(new ApolloConfigListener());
            }

            @Override
            public void run(SourceContext<String> ctx) throws Exception {
                while (true) {
                    String value = config.getProperty("change.value", "default");
                    ctx.collect(value);
                    logger.info("读取apollo配置 {}", value);
                    TimeUnit.SECONDS.sleep(1);
                }
            }

            @Override
            public void cancel() {

            }
        }).print("######");
        env.execute();
    }

}
ApolloConfigListener

/**
 * apollo配置监听器
 * @author songmin
 * @date 2022/7/14 15:20
 */
public class ApolloConfigListener implements ConfigChangeListener {

    private static final Logger logger = LoggerFactory.getLogger(ApolloConfigListener.class);

    @Override
    public void onChange(ConfigChangeEvent configChangeEvent) {
        logger.info(" #business Changes for namespace {}", configChangeEvent.getNamespace());
        for (String key : configChangeEvent.changedKeys()) {
            ConfigChange change = configChangeEvent.getChange(key);
            logger.info("Found change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
                    change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType());
        }
    }
}

 

posted @ 2022-07-14 18:13  执笔coding  阅读(283)  评论(0编辑  收藏  举报