Spring Boot + Spring Cloud 实现权限管理系统 后端篇(二十三):配置中心(Config、Bus)

 

在线演示

演示地址:

 分别编辑三个文件,配置 comsumer.hello 属性的值为 comsumer.hello=hello, this is xx configurations.

服务端实现

新建工程

新建 kitty-conifg 工程,作为配置中心的服务端,负责把GIT仓库的配置文件发布为RESTFul接口。

添加依赖

除了Spring Cloud依赖之外,添加配置中心依赖包。

pom.xml

复制代码
<!--spring config--><dependencies>    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-config-server</artifactId>    </dependency></dependencies>
复制代码

启动类

启动类添加注解 @EnableConfigServer,开启配置服务支持。

KittyConfigApplication.java

复制代码
package com.louis.kitty.config;  import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.config.server.EnableConfigServer;  @EnableConfigServer @EnableDiscoveryClient @SpringBootApplication public class KittyConfigApplication {      public static void main(String[] args) {         SpringApplication.run(KittyConfigApplication.class, args);     } }
复制代码

配置文件

修改配置文件,添加如下内容。如果是私有仓库需要填写用户名密码,如果是公开仓库,可以不配置密码。

application.yml

复制代码
server:   port: 8020 spring:   application:     name: kitty-config   cloud:     consul:       host: localhost       port: 8500       discovery:         serviceName: ${spring.application.name}    # 注册到consul的服务名称     config:
   label: master  # git仓库分支 server: git: uri: https:
//gitee.com/liuge1988/kitty.git # 配置git仓库的地址 search-paths: config-repo # git仓库地址下的相对地址,可以配置多个,用,分割。 username: username # git仓库的账号 password: password # git仓库的密码
复制代码

Spring Cloud Config也提供本地存储配置的方式,只需设置属性spring.profiles.active=native,Config Server会默认从应用的src/main/resource目录下检索配置文件。另外也可以通过spring.cloud.config.server.native.searchLocations=file:D:/properties/属性来指定配置文件的位置。虽然Spring Cloud Config提供了这样的功能,但是为了更好的支持内容管理和版本控制,还是比较推荐使用GIT的方式。

测试效果

启动注册中心,配置中心,访问 http://localhost:8020/kitty-consumer/dev,返回结果如下。

复制代码
{     "name": "kitty-consumer",     "profiles": ["dev"],     "label": null,     "version": "1320259308dfdf438f5963f95cbce9e0a76997b7",     "state": null,     "propertySources&q
                    
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信