SpringCloud配置中心--svn(二)

Myth丶恋晨 2021-11-26 08:22 448阅读 0赞

上章我们讲完server端,现在我们来client端

client 端

主要展示如何在业务项目中去获取server端的配置信息

1、添加依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-config</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-test</artifactId>
  13. <scope>test</scope>
  14. </dependency>

引入spring-boot-starter-web包方便web测试

2、配置文件

需要配置两个配置文件,application.propertiesbootstrap.properties

application.properties如下:

  1. spring.application.name=spring-cloud-config-client //项目名称
  2. server.port=8002
  3. bootstrap.properties如下:
  4. spring.cloud.config.name=server-config
  5. spring.cloud.config.profile=dev
  6. spring.cloud.config.uri=http://localhost:8001/ //server端地址
  7. spring.cloud.config.label=trunk

特别注意:上面这些与spring-cloud相关的属性必须配置在bootstrap.properties中,config部分内容才能被正确加载。因为config的相关配置会先于application.properties,而bootstrap.properties的加载也是先于application.properties。

3、启动类

启动类只需要@SpringBootApplication注解就可以

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. public class ConfigClientApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(ConfigClientApplication.class, args);
  7. }
  8. }

4、web测试

使用@Value注解来获取server端参数的值

  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. class HelloController {
  6. @Value("${hello}")
  7. private String hello;
  8. @RequestMapping("/hello")
  9. public String from() {
  10. return this.hello;
  11. }
  12. }

启动项目后访问:http://localhost:8002/hello
在这里插入图片描述

说明已经正确的从server端获取到了参数。到此一个完整的服务端提供配置服务,客户端获取配置参数的例子就完成了。

我们在进行一些小实验,手动修改server-config-dev.properties中配置信息为:hello=springCloud!!! update 提交到svn
在这里插入图片描述
再次在浏览器访问http://localhost:8002/hello
返回:springCloud!!! 说明获取的信息还是旧的参数,这是为什么呢?因为springboot项目只有在启动的时候才会获取配置文件的值,修改svn信息后,client端并没有在次去获取,所以导致这个问题。如何去解决这个问题呢?留到下一章我们在介绍。

发表评论

表情:
评论列表 (有 0 条评论,448人围观)

还没有评论,来说两句吧...

相关阅读