springboot2.1入门系列三 Springboot多环境配置

本文为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,就可以给应用做一个小的集群了。

本文内容到此结束,更多内容可关注公众号:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值