强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan
【前言】
在上一篇博文《灰度实战(一):Apollo配置中心(1)》中讲解了如何搭建Apollo以及创建配置文件,在本篇博文中为大家带来程序如何通过Apollo读取配置文件,以及配置中心一大亮点---配置修改后实时推送到应用端。
【实时推送演示】
一、程序连接Apollo配置
1、在项目pom中增加Apollo客户端依赖
<!-- apollo-client -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>${apollo-client.version}</version>
</dependency>
2、启动配置文件(application.yml)修改为(参数项说明参考:Java客户端使用实例)
app:
id: ${app_ip:gray_apollo}
apollo:
cluster: ${apollo_cluster:default}
bootstrap:
enabled: ${apollo_bootstrap:true}
name spaces: ${apollo_namespaces:grayapollo}
meta: ${apollo_meta:http://127.0.0.1:8080}
3、启动项目后,可以在Apollo配置中心看到注入一个实例
二、@value类型,程序演示
1、演示代码
package com.zhanghan.grayapollo.controller;
import com.zhanghan.grayapollo.util.wrapper.WrapMapper;
import com.zhanghan.grayapollo.util.wrapper.Wrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@Api(value = "演示Apollo控制器",tags = {"演示Apollo控制器"})
public class DynamicController {
@Value("${zh.int}")
private Integer zhInt;
@Autowired
private RedisTemplate<String, String> strRedisTemplate;
@ApiOperation(value="测试通过@value注入数据",tags = {"演示Apollo控制器"})
@RequestMapping(value = "/test/value", method = RequestMethod.POST)
public Wrapper testValue() {
Map<String, Object> map = new HashMap();
map.put("zhTest", zhInt);
return WrapMapper.ok(map);
}
}
2、启动项目后,在swagger中访问
3、在Apollo上修改zh.int的值
4、在Apollo上发布此次修改
5、查看项目日志(发现值已经推送到程序)
6、再次通过swagger访问此接口(惊奇发现程序值已修改为8)
7、小结:
以上为大家演示,在不用重启程序情况下,让配置文件改变@value读取值进行更改。
三、项目地址
灰度实战:https://github.com/dangnianchuntian/gray
【总结】
1、本节第一部分为大家演示Apollo动态更新@value值,这个功能应用特别实用,比如一些阈值的设定等等。
2、下一篇为大家演示如何接收Apollo动态更新连第三方中间件的连接池(以redis连接池为例)。