项目实战:携程Apollo使用

1. 简介

Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性,适用于微服务配置管理场景。
更详细的介绍请查看:https://github.com/ctripcorp/apollo

2. Apollo和Spring Cloud Config对比

在这里插入图片描述

3. 安装Apollo

安装步骤可以查看:https://blog.csdn.net/michael_hm/article/details/79412839
注意点:

  • 由于Apollo启动文件为demo.sh。直接使用windows无法启动.sh文件,此处我借助Git Bash Here进行脚本脚本执行。其他工具也可以。
  • 你本地的Java_home路径不能包含空格。否则会出现以下错误:
    在这里插入图片描述
    解决办法:更换Jdk安装目录。

4. Apollo配置中心配置

4.1 创建项目

访问http://localhost:8070 登录后,选择创建项目。如下图所示:
在这里插入图片描述

4.2 填写配置信息

在这里插入图片描述
配置说明:

  • 部门:选择应用所在的部门。(想自定义部门,参照官方文档,这里就选择样例)
  • 应用AppId:用来标识应用身份的唯一id,格式为string,需要和客户端。application.properties中配置的app.id对应。
  • 应用名称:应用名,仅用于界面展示。
  • 应用负责人:选择的人默认会成为该项目的管理员,具备项目权限管理、集群创建、Namespace创建等权限。

4.3 添加配置项

添加配置支持两种方式:

  • 单条添加
  • Text文本格式添加(key=value格式)
    在这里插入图片描述
    点击“新增配置”,效果图如下所示:
    在这里插入图片描述
    点击“提交”即可。

4.4 发布配置

点击发布即可,可以选择性的填写修改记录,效果图如下图所示:在这里插入图片描述

5. SpringBoot+Apollo

需求

日志模块是每个项目中必须的,用来记录程序运行中的相关信息。一般在开发环境下使用DEBUG级别的日志输出,为了方便查看问题,而在线上一般都使用INFO或者ERROR级别的日志,主要记录业务操作或者错误的日志。那么问题来了,当线上环境出现问题希望输出DEBUG日志信息辅助排查的时候怎么办呢?修改配置文件,重新打包然后上传重启线上环境,以前确实是这么做的。

虽然上面我们已经把日志的配置部署到Apollo配置中心,但在配置中心修改日志等级,依然需要重启应用才生效,下面我们就通过监听配置的变化,来达到热更新的效果。

apoller配置文件内容如下:

spring.application.name = ec-voicesystem
server.port = 8831
logging.level.cn.thislx.apollo.controller = info

application.properties配置文件如下:

app.id=leimingtech-springboot-apollo
apollo.meta=http://192.168.30.128:8080
apollo.bootstarp.enabled=true
apollo.bootstrap.eagerLoad.enabled=true
logging.level.cn.thislx.apollo.controller=debug

配置说明:

  • app.id:AppId是应用的身份信息,是配置中心获取配置的一个重要信息。
  • apollo.bootstrap.enabled:在应用启动阶段,向Spring容器注入被托管的application.properties文件的配置信息。
  • apollo.bootstrap.eagerLoad.enabled:将Apollo配置加载提到初始化日志系统之前。
  • logging.level.com.gf.controller:调整 controller 包的 log 级别,为了后面演示在配置中心动态配置日志级别。

需要添加的依赖 如下:

<dependency>
    <groupId>com.ctrip.framework.apollo</groupId>
    <artifactId>apollo-client</artifactId>
    <version>1.1.0</version>
</dependency>

<!-- 以下两个非必选 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8.1</version>
</dependency>

启动类代码如下所示:

package cn.thislx.apollo;

import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


/**
 * @Author: LX 17839193044@162.com
 * @Description: 启动类必须增加@EnableApolloConfig
 * @Date: 2019/4/16 20:03
 * @Version: V1.0
 */
@SpringBootApplication
//@EnableDiscoveryClient
@EnableApolloConfig
public class ApolloApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApolloApplication.class, args);
    }

}

读取公共apollo配置工具类代码如下:

package cn.thislx.apollo.utils;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;

import java.util.Properties;

/**
 * @Author: LX 17839193044@162.com
 * @Description: 读取公共apollo配置
 * @Date: 2019/4/16 20:03
 * @Version: V1.0
 */
public class PropertiesUtils {
    private static final String COMMON = "nova1.NovaCommon";
    public static Properties properties = new Properties();

    static {
        Config commonConfig = ConfigService.getConfig(COMMON);
        if (commonConfig != null) {
            for (String key : commonConfig.getPropertyNames()) {
                properties.setProperty(key, commonConfig.getProperty(key, null));
            }
        }
    }
}

监听apollo配置更新配置类代码如下:

package cn.thislx.apollo.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * @Author: LX 17839193044@162.com
 * @Description: 监听apollo配置更新配置类
 * @Date: 18:45 2019/4/16
 * @Version: V1.0
 */
@Configuration
public class LoggerConfig {

    private static final Logger logger = LoggerFactory.getLogger(LoggerConfig.class);
    private static final String LOGGER_TAG = "logging.level.";

    @Autowired
    private LoggingSystem loggingSystem;

    /**
     * @ApolloConfig注解: 将Apollo服务端的中的配置注入这个类中。
     */
    @ApolloConfig
    private Config config;

    /**
     * @param changeEvent:可以获取被修改配置项的key集合,以及被修改配置项的新值、旧值和修改类型等信息。
     * @ApolloConfigChangeListener注解: 监听配置中心配置的更新事件,若该事件发生,则调用refreshLoggingLevels方法,处理该事件。
     */
    @ApolloConfigChangeListener
    private void configChangeListter(ConfigChangeEvent changeEvent) {
        refreshLoggingLevels();
    }


    /**
     * @Author: LX 17839193044@162.com
     * @Description: apollo文件修改执行。实现实时更新日志打印级别
     * @Date: 2019/4/16 20:11
     * @Version: V1.0
     */
    @PostConstruct
    private void refreshLoggingLevels() {
        Set<String> keyNames = config.getPropertyNames();
        for (String key : keyNames) {
            if (StringUtils.containsIgnoreCase(key, LOGGER_TAG)) {
                String strLevel = config.getProperty(key, "info");
                LogLevel level = LogLevel.valueOf(strLevel.toUpperCase());
                loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);
                logger.info("{}:{}", key, strLevel);
            }
        }
    }

}

测试Controller代码如下:

package cn.thislx.apollo.controller;


import cn.thislx.apollo.utils.PropertiesUtils;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Properties;
import java.util.Set;

/**
 * @Author: LX 17839193044@162.com
 * @Description: 测试获取apollo配置controller
 * @Date: 9:36 2019/4/16
 * @Version: V1.0
 */
@Slf4j
@RestController
@RequestMapping("/apollo")
public class IndexController {


    /**
     * 可以直接使用注解获取apollo中的配置信息
     */
    @Value("${server.port}")
    private String port;

    /**
     * 从apollo获取配置信息
     */
    @ApolloConfig
    private Config config;

    /**
     * @Author: LX 17839193044@162.com
     * @Description: 打印apollo的索引配置类
     * @Date: 2019/4/16 19:59
     * @Version: V1.0
     */
    @GetMapping("/index")
    public Properties apolloReadDemo() {
        /**
         * 得到当前app.id中的配置
         * */
        Set<String> set = config.getPropertyNames();
        for (String key : set) {
            PropertiesUtils.properties.setProperty(key, config.getProperty(key, null));
        }
        for (String key : PropertiesUtils.properties.stringPropertyNames()) {
            System.out.println(key + ":" + PropertiesUtils.properties.getProperty(key));
        }
        return PropertiesUtils.properties;
    }


    /**
     * @Author: LX 17839193044@162.com
     * @Description: 测试修改apollo配置文件热更新
     * @Date: 2019/4/16 19:54
     * @Version: V1.0
     */
    @GetMapping("testHotUpdate")
    public String testHotUpdate() {
        log.debug("debug log...");
        log.info("info log...");
        log.warn("warn log...");
        return "port:" + port;
    }
}

修改 apollo中的logging.level.cn.thislx.apollo.controller对应的日志级别,调用http://ip:port/apollo/testHotUpdate ,观察日志修改前后日志打印情况。发现已经实现日志配置文件的热更新了。

源码地址:https://github.com/lxwjq/SpringBoot-Apollo

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
root@in_dev_docker:/apollo# bash scripts/msf_create_lossless_map.sh /apollo/hdmap/pcd_apollo/ 50 /apollo/hdmap/ /apollo/bazel-bin WARNING: Logging before InitGoogleLogging() is written to STDERR E0715 22:08:35.399576 6436 lossless_map_creator.cc:162] num_trials = 1 Pcd folders are as follows: /apollo/hdmap/pcd_apollo/ Resolution: 0.125 Dataset: /apollo/hdmap/pcd_apollo Dataset: /apollo/hdmap/pcd_apollo/ Loaded the map configuration from: /apollo/hdmap//lossless_map/config.xml. Saved the map configuration to: /apollo/hdmap//lossless_map/config.xml. Saved the map configuration to: /apollo/hdmap//lossless_map/config.xml. E0715 22:08:35.767315 6436 lossless_map_creator.cc:264] ieout_poses = 1706 Failed to find match for field 'intensity'. Failed to find match for field 'timestamp'. E0715 22:08:35.769896 6436 velodyne_utility.cc:46] Un-organized-point-cloud E0715 22:08:35.781770 6436 lossless_map_creator.cc:275] Loaded 245443D Points at Trial: 0 Frame: 0. F0715 22:08:35.781791 6436 base_map_node_index.cc:101] Check failed: false *** Check failure stack trace: *** scripts/msf_create_lossless_map.sh: line 11: 6436 Aborted (core dumped) $APOLLO_BIN_PREFIX/modules/localization/msf/local_tool/map_creation/lossless_map_creator --use_plane_inliers_only true --pcd_folders $1 --pose_files $2 --map_folder $IN_FOLDER --zone_id $ZONE_ID --coordinate_type UTM --map_resolution_type single root@in_dev_docker:/apollo# bash scripts/msf_create_lossless_map.sh /apollo/hdmap/pcd_apollo/ 50 /apollo/hdmap/
最新发布
07-16

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值