Spring Cloud可以添加config模块为微服务做分布式配置,支持git和本地文件存储,但是最为分布式配置服务,本地存储最好仅用于测试,不然多服务器的文件系统同步是一个障碍。下面列出配置文件和代码,搭建一个分布式配置服务server。
application.yml
#APP config
REGISTRY_SERVER_URL: http://127.0.0.1:8761/eureka/
#Rabbit config
RABBITMQ_SERVER_HOST: 192.168.1.13
RABBITMQ_SERVER_PORT: 5672
RABBITMQ_SERVER_USERNAME: cloud
RABBITMQ_SERVER_PASSWORD: cloud
logging.file: logs/${spring.application.name}.log
logging.level.root: INFO
logging.level.cn.gaiasys: DEBUG
server:
port: 8888
tomcat:
max-threads: 128
min-spare-threads: 64
spring:
application:
name: config-server
main:
banner-mode: "on"
mvc:
favicon.enabled: false
rabbitmq:
host: ${RABBITMQ_SERVER_HOST}
port: ${RABBITMQ_SERVER_PORT}
username: ${RABBITMQ_SERVER_USERNAME}
password: ${RABBITMQ_SERVER_PASSWORD}
cloud:
config:
server:
git:
uri: https://github.com/renchhao/ms-config.git
searchPaths: ms-config
username:
password:
native:
search-locations: classpath:/ms-config
overrides:
REGISTRY_SERVER_URL: ${REGISTRY_SERVER_URL}
spring.rabbitmq.host: ${RABBITMQ_SERVER_HOST}
spring.rabbitmq.port: ${RABBITMQ_SERVER_PORT}
spring.rabbitmq.username: ${RABBITMQ_SERVER_USERNAME}
spring.rabbitmq.password: ${RABBITMQ_SERVER_PASSWORD}
#如果要启用本地配置文件提供服务,修改为native
spring.profiles.active: git
参考:http://cloud.spring.io/spring-cloud-static/Camden.SR5/#_spring_cloud_config
具体的说明在上面配置文件中已经有注释,需要注意的是
native
的方式,路径是file://
打头,如果是windows环境需要多加一个/
。如果路径是file://
打头,则默认在[classpath:/, classpath:/config, file:./, file:./config]
这些路径下进行搜索,如果相对目录,请带上classpath
,不能直接./ms-config
。
新建一个application启动类
ConfigServerApplication.java
/**
* 分布式配置服务.
* @author Wang.ch
*/
@EnableConfigServer
@SpringBootApplication
@EnableDiscoveryClient
public class ConfigServerApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigServerApplication.class).web(true).run(args);
}
}
build.gradle
dependencies {
compile("org.springframework.cloud:spring-cloud-config-server")
compile("org.springframework.cloud:spring-cloud-starter-eureka")
}
这个时候就可以访问:http://localhost:8888/account/prod,
config支持的url访问搜索路径:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties