20.0、springcloud-Config-客户端连接服务端访问远程【简单初体验】
首先我们创建一个configclient.yaml文件,如下:
spring:
profiles:
active: dev
---
server:
port: 8201
#spring配置
spring:
profiles: dev
application:
name: springcloud-provider-dept
#Eureka的配置,服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://localhost:7002/eureka/
---
server:
port: 8202
#spring配置
spring:
profiles: test
application:
name: springcloud-provider-dept
#Eureka的配置,服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://localhost:7002/eureka/
然后将这个文件push到远程仓库,【远程仓库如何创建之前 18.0的环境搭建 有说~】
第一步:创建一个新 module,springcloud-config-client-3355
第二步:在pom.xml中导入相关的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--actuator完善监控信息-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
第三步:配置 bootstrap.yaml 文件
#项目系统级别的配置,而application.yaml是用户级别的的配置
spring:
cloud:
config:
name: configclient #需要从git上读取的资源的名称,不需要后缀
profile: dev
label: master
uri: http://localhost:3344
【注意】
这里的name属性是上面push到远程仓库的那个配置文件名
profile是获取 多环境配置文件中 的哪一个环境配置,这里获取的是dev开发环境
label是从哪一个分支获取,这里是从master主分支获取
url 就是访问的端口号
application.yaml,如下:
#用户级别的配置
spring:
application:
name: springcloud-config-client-3355
这里用的是 bootstrap 而不是 application 的原因是因为 bootstrap 是系统级别的配置,而application 是用户级别的配置【系统级的优先级比用户级更高】,我们这里需要去连接远程端为了防止冲突所以配置优先级更高的 bootstrap。
本地的服务相当于是一个中转站,客户端先访问中转站然后又中转站去访问远程端
第四步:配置主启动类Config_Client_3355.java:
package com.hkl.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Config_Client_3355 {
public static void main(String[] args) {
SpringApplication.run(Config_Client_3355.class,args);
}
}
第五步:创建一个ConfigController.java :
package com.hkl.springcloud.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigClientController {
@Value("${spring.application.name}")
private String applicationName;
@Value("${eureka.client.service-url.defaultZone}")
private String eurekaServer;
@Value("${server.port}")
private String port;
@RequestMapping("/config")
public String getConfig() {
return "applicationName:"+applicationName +
"eurekaServer:"+eurekaServer +
"port:"+port;
}
}
这里写了一个接口 /config , 是为了待会可以用这个接口来测试能不能拿到远程仓库的信息
Ok,做完这些来测试一下,首先用3344端口先去访问一下远程仓库 http://localhost:3344/master/configclient2-dev.yaml,看能不能访问到configclient.yaml文件
然后成功访问后,启动3355客户端,用http://localhost:8201/config访问测试一下能不能拿到【这里用8201端口访问是因为configclient.yaml文件中启动的是8201 dev 端口,如果换成启动8202端口test的话就会变成8202】,如下图所示成功拿到了远程端的配置信息即可: