Spring Cloud入门1-config配置中心

来源:互联网 发布:网络软文兼职 编辑:程序博客网 时间:2024/05/01 14:54

spring Cloud Config

配置管理工具包,让你可以把配置放到远程服务器,集中化管理集群配置,目前支持本地存储、Git以及Subversion。

也就是说,我们可以使用Spring Cloud Config来获取远程服务器上的配置信息。


可以分为两个部分:

服务端: 配置服务端,服务管理配置信息
客户端:客户端调用server端暴露接口获取配置信息


代码可以通过 start.spring.io 去生成,服务端选择 web、config-server

服务端代码:

在程序application中添加@EnableConfigServer注解,表明这是一个Config Server端

    @SpringBootApplication      @EnableConfigServer      public class SpringcloudConfigApplication {                public static void main(String[] args) {              SpringApplication.run(SpringcloudConfigApplication.class, args);          }      }  

在application.properties中配置远程仓库信息

# 端口号server:  port: 8081 # 使用本地测试环境 spring:  profiles:    active: native      cloud:    config:      server:        native:          search-locations: classpath:/config/
config 下面有  jdbc-test.yml 文件,文件里面有个属性:userName = test-01


客户端代码:

代码可以通过 start.spring.io 去生成,选择 web、config-client,端口号8082

必须要有 bootstrap.yml 文件

# 指定配置中心 spring:  cloud:    config:      uri: http://localhost:8081      profile: test      label: master        # 指定属性文件名 jdbc-*.yml,是有命名规则的     application:    name: jdbc

访问参数代码

@SpringBootApplication@RestController@RefreshScopepublic class ClientConfigApplication {@Value("${userName}")private String userName;@GetMapping(value = "/get")public String testGet() {return "hello" + userName;}public static void main(String[] args) {SpringApplication.run(ClientConfigApplication.class, args);}}

这样可以通过客户端 http://localhost:8082/get  访问到 服务端 userName 的属性值,

下一步,把 服务端 jdbc-test.yml 里面 userName 的值改为  test-02,  不重启服务,继续在客户端访问 http://localhost:8082/get ,发现访问到的值还是原来的值,

客户端并没有改变,这个时候需要我们 手动引入 spring-cloud 的监控模块,spring-boot-starter-actuator,

在pom 文件里面引入包

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-actuator</artifactId>        </dependency>

在客户端读取属性的类上面加入标注 @RefreshScope ,然后在 config-client 端执行POST 请求 http://localhost:8082/refresh 就可以更新刷新配置变量到内存中了,

在执行 http://localhost:8082/get ,值就变了,

另外需要注意的是,如果spring-boot 的版本是1.5.x 之后的,自动加了权限验证,默认是开启的,需要关闭,

在application.yml 中加入 management.security.enabled=false  ,就ok了。












原创粉丝点击