栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot集成Apollo

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot集成Apollo

SpringBoot集成Apollo

1. 集成Apollo2. 测试是否集成成功

项目结构图:

1. 集成Apollo

集成Apollo有2个步骤,首先是要引入Apollo的客户端,接着需要在springboot核心配置文件中引入需要从Apollo中注入的配置信息。

①引入依赖
在hailtaxi-driver的pom.xml中引入如下依赖:

        
        
            com.ctrip.framework.apollo
            apollo-client
            1.7.0
        

②修改配置
在 driver项目的bootstrap.yml 中写上如下配置:

server:
  port: 18081
#Apollo应用
app:
  id: hailtaxi-driver-config  #使用的 Apollo 的项目(应用)编号
apollo:
  meta: http://192.168.211.145:8080 #Apollo meta Server 地址
  bootstrap:
    enabled: true   #是否开启 Apollo 配置预加载功能。默认为 false。
    eagerLoad:
      enable: true  #是否开启 Apollo 支持日志级别的加载时机。默认为 false。
    namespaces: application,stmt,driver-info,springboot-config  #使用的 Apollo 的命名空间,默认为 application。
2. 测试是否集成成功

为了将更多资源交给Apollo,我们在 hailtaxi-driver-config 中添加一个新的namespace,用于配置springboot的核心配置springboot-config内容如下:

spring.application.name = hailtaxi-driver
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://192.168.211.145:3306/hailtaxi-driver?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = 123456
spring.cloud.consul.host = 192.168.211.145
spring.cloud.consul.port = 8500
spring.cloud.consul.discovery.service-name = ${spring.application.name}
spring.cloud.consul.discovery.prefer-ip-address = true

我们编写一个案例,获取配置中的数据(stmt、driver-info),并对外输出友好提示,在hailtaxi-driver 中创建代码如下:

@RestController
@RequestMapping(value = "/trip")
//@ConfigurationProperties(prefix = "platform")
@Data
public class TripController {

    @Autowired
    private Environment environment;

    @Value("${ip}")
    private String ip;

    private String name;
    private String address;
    private String coursename;

    
    @GetMapping(value = "/message")
    public String message(){
        //获取hailtaxi-driver-config中stmt数据
        String ip = environment.getProperty("ip");
        String city = environment.getProperty("city");
        String weather = environment.getProperty("weather");

        //获取hailtaxi-driver-config中driver-info数据
        String drivertype = environment.getProperty("drivertype");

        //组装提示信息
        String message = "您的IP【"+ip+"】,欢迎【"+
                city+"】用户,当前天气"+weather+"。您选择的车型为【"+
                drivertype+"】,祝您出行愉快!【"+
                name+"】来自于【"+coursename+"】,联系地址:"+address;
        return message;
    }
}

我们请求 http://localhost:18081/trip/message 进行测试,效果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703696.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号