配置中心

最近更新时间:2021-09-07 17:00:41

查看PDF

准备工作

开始实践配置中心功能前,请确保已完成了 SDK 下载。
配置中心依赖consul作为配置中心,需要本地安装consul,consul下载和安装参考官网https://www.consul.io。

一、创建config-demo工程
从微服务平台下载一个项目,命名为config-demo。
图片.png

二、依赖项
修改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”。
9.png

文档内容是否对您有帮助?

根本没帮助
文档较差
文档一般
文档不错
文档很好

在文档使用中是否遇到以下问题

内容不全,不深入
内容更新不及时
描述不清晰,比较混乱
系统或功能太复杂,缺乏足够的引导
内容冗长

更多建议

0/200

评价建议不能为空

提交成功!

非常感谢您的反馈,我们会继续努力做到更好!

问题反馈