分布式配置中心:Spring Cloud Config (五)使用笔记

config服务端

在spring-cloud-demo工程中添加module:config-server
在pom.xml文件中加入依赖:

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

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

在resource目录下增加application.properties文件,添加如下内容:

server.port=8888
spring.application.name=config-server

eureka.client.serviceUrl.defaultZone=http\://localhost\:8761/eureka/
spring.profiles.active=native
spring.cloud.config.server.native.searchLocations=classpath:/properties/

在resource目录下创建目录:properties,在目录下增加文件:cloud-config-dev.properties,内容如下

msg=hello, I'm from config-server

在java目录下创建一个SpringBoot项目启动类:ConfigServer,内容如下:

/**
 * @CalssName ConfigServer
 * @Description TODO
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServer {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServer.class,args);
    }
}

config使用端

在spring-cloud-demo工程中添加module:config-use
在pom.xml文件中加入依赖:

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

在resource目录下增加application.properties文件,添加如下内容:

server.port=9802
spring.application.name=config-use
eureka.client.serviceUrl.defaultZone=http\://localhost\:8761/eureka/

spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.service-id=config-server
spring.cloud.config.name=cloud-config
spring.cloud.config.profile=${config.profile:dev}

在java目录下创建一个SpringBoot项目启动类:ConfigUseApplication,内容如下:

/**
 * @CalssName ConfigUse
 * @Description TODO
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ConfigUseApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigUseApplication.class, args);
    }
}

创建一个Controller:HelloController,内容如下:

/**
 * @CalssName HelloController
 * @Description TODO
 */
@RestController
public class HelloController {
    @Value("${msg}")
    private String msg;

    @RequestMapping("/msg")
    public String msg() {
        return msg;
    }
}

以此启动Eureka服务端、config-server和config-use,浏览器访问:http://localhost:9802/msg,输出如下:

hello, I'm from config-server

说明配置中心应用成功

猜你喜欢

转载自www.cnblogs.com/yhongyin/p/11183863.html