开始实践配置中心功能前,请确保已完成了 SDK 下载。
配置中心依赖consul作为配置中心,需要本地安装consul,consul下载和安装参考官网https://www.consul.io。
一、创建config-demo工程
从微服务平台下载一个项目,命名为config-demo。
二、依赖项
修改pom.xml中dependency依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.ksyun.kmse</groupId>
<artifactId>spring-cloud-kmse-starter-consul-config</artifactId>
<version>${version}</version>
</dependency>
三、修改配置
bootstrap.yml文件中添加如下配置。
spring:
application:
name: config-demo
cloud:
consul:
host: http://127.0.0.1
port: 8500
config:
prefix: config
enabled: true
format: YAML
data-key: data
四、添加代码
使用@Value和@RefreshScope注解,添加对应的配置项。
package com.demo.x.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.cloud.context.config.annotation.RefreshScope;
@RequestMapping({"/account"})
@RestController
@RefreshScope
public class AccountController {
private static final Logger log = LoggerFactory.getLogger(AccountController.class);
@Value("${info}")
private String info;
@GetMapping({"/{id}"})
public String account(@PathVariable("id") Integer id) {
log.info("调用account " + id);
return id + ":"+info;
}
}
五、轻量级服务注册中心下发动态配置
进入consul控制台页面,添加名config/config-demo/data的key,value填写“info: hello”。
文档内容是否对您有帮助?
评价建议不能为空
非常感谢您的反馈,我们会继续努力做到更好!