springCloud系列(6)之Config远程配置文件

在微服务的项目中,经常会有很多的的配置文件,太多的配置文件不利于后期修改,为减少配置文件的处理,这时候会使用springCloud中的config模块进行开发处理,

Config分为server服务端和client客户端,我们把常用的配置放在远程工具(git,SVN,码云)上,然后Config服务端从远程工具上下载需要的配置,然后客户端获取这些配置,最后使用配置

简单使用

1、在码云上编写配置文件 config-dev.yml ,其实就是一个普通的配置文件,配置文件名上最好加-,这样方便后面配置文件的编写

server:
  port: 8085
spring:
  application:
    name: user-provider
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false
    password: root
    username: root
mybatis:
  type-aliases-package: com.lihao
  mapper-locations: classes:mapper/*Mapper.xml
eureka:
  client:
    service-url:
      defaultZone: http://root:123456@localhost:7776/eureka/

2、编写config-server项目负责从码云上下载对应配置

首先在原来的springCloud项目依赖前提下增加新的依赖

<!-- config -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

增加配置文件application.yml

server:
  port: 7000
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri:  https://gitee.com/lihao2/config-server.git
eureka:
  client:
    service-url:
      defaultZone: http://root:123456@localhost:7776/eureka/

在启动类上添加@EnableConfigServer注解,最后运行启动类

启动后访问http://localhost:7000/config-dev.yml 可以看到自己写的配置文件内容说明成功

3、编写config-client

这里的客户端其实指的就是生产者或者消费者,我们直接在生产者端添加依赖即可,首先在user-provider下添加maven依赖

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

在resources目录下创建bootstrap.yml文件,bootstrap.yml作用类似于application.yml,不同的是它在application.yml之前执行

注意name的值和profile的值就是在Git中配置文件的名称
我的配置文件名是config-dev,所以下面的name值是config,profile的值是dev

spring:
  application:
    name: config
  cloud:
    config:
      uri: http://localhost:7000/
      profile: dev
      

手动刷新

目前config的使用已经结束,但是在实际编程中有的时候需要直接更改远程文件的配置,但是这时候不能直接使用,需要重启服务,那么能不能不重启项目,可以直接使用呢?下面的配置讲的是完成不重启项目,直接手动刷新配置

为了方便展示手动刷新效果,首先我们在在远程gitee上添加profile属性,什么值无所谓,主要用于展示刷新配置的效果

profile: one

在config-client中添加jar包,也就是服务的生产者或消费者,在本项目中就是user-provider

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

在配置文件bootstrap.yml添加下面的设置,取消springBoot验证

management:
  security:
    enabled: false

最后是controller类

@RestController
@RefreshScope
public class UserService {

	// 获取配置中的profile值,并注入
    @Value("${profile}")
    private String profile;

    @RequestMapping("t")
    public String test(){
        System.out.println(profile);
        return "success";
    }
}

然后测试

首先所有都启动,然后修改远程中profile的值,然后访问 生产者端的 /refresh 路径,注意访问方式是POST,这时候就完成了手动刷新,可以在生产者端的打印日志上看到,打印的就是最新的值了

猜你喜欢

转载自blog.csdn.net/lihao1107156171/article/details/114296560
今日推荐