使用 maven 的 `wagon-maven-plugin`插件 快速部署 到不同的 环境

profile

在pom文件中配置 开发和测试环境的 profile信息,

   <profiles>
        <profile>
            <!-- 开发环境 -->
            <id>dev</id>
            <properties>
                <user>root</user>
                <password>root</password>
                <ip>192.168.233.123</ip>
                <active>dev</active>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <!-- 测试环境 -->
            <id>test</id>
            <properties>
                <user>root</user>
                <password>root</password>
                <ip>192.168.233.124</ip>
                <active>test</active>
            </properties>
        </profile>
    </profiles>

引入插件

 <build>
     <!-- maven扩展 提供ssh远程服务 是wagon-maven-plugin插件所依赖 -->
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-ssh</artifactId>
                <version>2.8</version>
            </extension>
        </extensions>

        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>wagon-maven-plugin</artifactId>
                <version>1.0</version>
                <configuration>
                    <!-- 拷贝目录下(执行目录) target目录下的jar包 --> 
                    <fromFile>target/${project.artifactId}${activeName}-${project.version}.jar</fromFile>
                    <!-- 使用scp传输文件 指定服务端 用户名密码 ip 并指定目标文件夹-->
                    <url>scp://${user}:${password}@${ip}/home/app/server</url>
                    <!-- 命令列表 可以在传输完成后执行 -->
                    <commands>
                        <command>systemctl restart boot-server</command>
                    </commands>
                    <!-- 显示运行命令的输出结果 -->
                    <displayCommandOutputs>true</displayCommandOutputs>
                </configuration>
            </plugin>
        </plugins>
    </build>

更多用法 请查看官网

  1. 将 profile中配置的变量 作为 连接的参数 这样指定profile后 就可以动态的拷贝的相应的文件夹

  2. 执行命令:mvn clean package -Ptest wagon:upload-single wagon:sshexec

    这个命令分成三个部分

    • mvn clean package -Ptest 指定profile 并打包

    • wagon:upload-single 上传命令

    • wagon:sshexec 执行配置的命令列表

    可以酌情选择

使用maven profile 替换 spring 的profile

上面是将项目按照指定的profile打包并上传到服务器 , 但是如果你的springboot项目 也配置了多个 环境,那么在执行时也需要 指定对应的 spring profile ,

可以 使用maven的profile 代替 spring的profile 那么当打包完成后 就无须在启动时重新指定

在application.yml 中配置:

spring:
    profiles:
        active: @active@

使用@@ 取maven profile中配置的变量, 如上例配置了maven的profile为test 等价于spring.profiles.active=test 这样就会读取到 application-test.yml里面的配置了

这里我一直都犯了一个错误: 我一直以为 当执行jar包指定了profile后 则会读取 相应的 application-{profile}.yml文件,不会读取 默认的application.yml了,其实不然 正确的读取顺序是,无论如果都会先读取默认文件夹下面 application.yml 再根据有没有指定profile ,去找对应的 yaml,并覆盖之前相同的配置(互补) 这也能解释为什么 profile配置在 application.yml 中可以生效的原因

原文地址:https://www.cnblogs.com/xjwhaha/p/13590438.html