Spring Cloud之分布式配置中心

本文介绍如何使用Spring Cloud Config搭建配置服务器和服务客户端,通过示例代码展示了配置服务器的基本设置、客户端连接配置服务器的方式及如何读取配置文件中的属性。

用服务的方式来实现

ConfigAppApplication.java

package com.packtpub.ConfigApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;

@EnableDiscoveryClient
@EnableConfigServer
@SpringBootApplication
public class ConfigAppApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(ConfigAppApplication.class).web(true).run(args);
    }
}

application.properties
spring.application.name=config-server
server.port=7001

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

spring.profiles.active=native
spring.cloud.config.server.native.searchLocations=file:D:/temp/

ConfigClientApplication.java

package com.packtpub.ConfigClient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class ConfigClientApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(ConfigClientApplication.class).web(true).run(args);
    }
}

bootstrap.properties

spring.application.name=didispace
server.port=7002

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.serviceId=config-server

spring.cloud.config.profile=test
#spring.cloud.config.label=master
#spring.cloud.config.uri=http://localhost:7001/

TestController.java

package com.packtpub.ConfigClient;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RefreshScope
@RestController
public class TestController {
    
    @Value("${from}")
    private String from;
    
    @RequestMapping("/from")
    public String from() {
        return this.from;
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值