本文为Spring Boot2.1系列的第三篇,代码可以从github下载 https://github.com/yinww/demo-springboot2.git
软件运行时可以有开发环境、测试环境、预发布环境、生产环境等多种环境,对应的环境配置参数的值可能不一样。Springboot提供了针对多环境的配置,可以通过运行时指定不同的properties文件或者yml实现。
也可以通过不同的配置文件实现集群的配置管理,比如在不同的配置文件中指定不同的端口或者日志文件路径等,再结合nginx实现简单的集群环境。
一、创建工程demo003
pom.xml的内容为
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yinww</groupId>
<artifactId>demo-springboot2</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>demo003</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
二、Java代码
主类
package com.yinww.demo.springboot2.demo003;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo003Application {
public static void main(String[] args) {
SpringApplication.run(Demo003Application.class, args);
}
}
Controller
package com.yinww.demo.springboot2.demo003.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/")
public String hello() {
return "Hello SpringBoot";
}
}
三、多环境配置文件
application.properties 配置通用的内容
spring.application.name=demo003
application-test1.properties test1的配置内容
server.port=10031
application-test2.properties test2的配置内容
server.port=10032
四、运行
分别执行
java -jar demo003-0.0.1-SNAPSHOT.jar --spring.profiles.active=test1
java -jar demo003-0.0.1-SNAPSHOT.jar --spring.profiles.active=test2
分别访问 http://localhost:10031/ 和 http://localhost:10032/
浏览器都显示相同的内容 Hello SpringBoot
如果再配合nginx,就可以给应用做一个小的集群了。
本文内容到此结束,更多内容可关注公众号: