Spring Cloud 配置文件切换(profiles的应用)

SpringCloud项目读取多种配置

一种是properties文件,一种是yml文件,两种文件格式都支持多种配置(profiles)。
如果没有profiles属性的话,properties与yml文件转换相对简单,

  • 一个是"."一个是双空格;

简单例子:
application.yml

server:
  port: 8888

application.properties

server.port=8888

如果有profiles属性,多种配置后怎么办

举个Eureka的例子
启动类代码

@SpringBootApplication
@EnableEurekaServer
public class FirstServer {
	public static void main(String[] args) {
		// 读取控制台输入,决定使用哪个profiles
		Scanner scan = new Scanner(System.in);
		String profiles = scan.nextLine();
		new SpringApplicationBuilder(FirstServer.class).profiles(profiles).run(args);
	}
}

用yml配置
application.yml配置文件

server:
  port: 8761
spring:
  application:
    name: first-cloud-server
  profiles: slave1
eureka:
  instance:
    hostname: slave1
  client:
    serviceUrl:
      defaultZone: http://slave2:8762/eureka/
---
server:
  port: 8762
spring:
  application:
    name: first-cloud-server
  profiles: slave2
eureka:
  instance:
    hostname: slave2
  client:
    serviceUrl:
      defaultZone: http://slave1:8761/eureka/

实际启动时,配置文件中用三个"-"分隔两种配置即可,只用输入slave1,slave2,便可分别按照配置启动。

用properties配置
properties文件的特性,你不能有两个同样的key,便不可能在同一文件中写两种配置,但Spring提供了如下的读取方式

  • 多少个配置就要有多少个配置文件,命名有要求application-“profilesName”.properties,这个profilesName便是你的配置名。
  • properties文件的内容要有
    cusvar=profilesName
    spring.profiles.active=profilesName

application-slave1.properties

cusvar=slave1
spring.profiles.active=slave1
server.port=8761
spring.application.name=first-cloud-server
eureka.instance.hostname=slave1
eureka.client.serviceUrl.defaultZone=http://slave2:8762/eureka/

application-slave2.properties

cusvar=slave2
spring.profiles.active=slave2
server.port=8762
spring.application.name=first-cloud-server
eureka.instance.hostname=slave2
eureka.client.serviceUrl.defaultZone=http://slave1:8761/eureka/

只用输入slave1,slave2,便可分别按照配置启动。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值