DevOps: 使用Maven插件实现分环境配置和版本检查

栏目: 编程工具 · 发布时间: 5年前

内容简介:DevOps是Development和Operations的组合词,作为一名软件工程师或者系统架构师,对于系统的开发和部署需要有充分的了解和把控。下面我们通过一个故事,把软件发布中的分环境配置和版本检查的解决方案为你娓娓道来......本文涉及到的所有代码可以在这里 :point_right:
DevOps: 使用Maven插件实现分环境配置和版本检查

DevOps是Development和Operations的组合词,作为一名软件工程师或者系统架构师,对于系统的开发和部署需要有充分的了解和把控。

下面我们通过一个故事,把软件发布中的分环境配置和版本检查的解决方案为你娓娓道来......

本文涉及到的所有代码可以在这里 :point_right: maven-devops 获取。

一个故事(事故)

试想这样一个场景,你做了一个功能: 每天凌晨4点去某个系统拉取一份数据邮件,然后第二天上午6点以邮件的形式发给你的老板。

首先你在自己的电脑上开发和测试,确认开发完成以后,把代码打包放到测试服务器上跑了一下。

你找到可爱的测试小妹妹,经过严格的测试,确认通过了所有测试用例。最后你不忘恭维一下测试小妹妹最近烫的头发真漂亮,并含蓄地表示有空想请她看最近上映的漫威电影。( 而实际上测试小妹妹的头发没有烫过,她也没听懂你的暗示,她更不喜欢看漫威的电影,最最关键的是,你根本没有时间请别人看电影——这个问题问一下你家里洗衣机里静静趟了两星期的袜子就知道了。)

你把自己的代码合并到主分支,然后通知发布人员把代码发布到生产环境。当你收到运维人员发布成功的提醒的时候,抬头看看表已经是午夜两点了。你喝干净杯子里的咖啡,深深懒腰,搭车回家了。

第二天上午,你在一阵急促的电话铃声中被吵醒,电话那头的声音顿时让你困意全无:老板没有收到任何邮件,邮件里的资料要在2h以后的一个重要会议中使用!

......

数据终于是想方设法搞到了,但疲惫、恐惧、羞耻和自责已经淹没了你的头脑,你要搞事情了:查到原因,彻底解决这个问题!

笨人和聪明人的差异就在于,笨人只会不停地栽跟头,而聪明人跌倒以后爬起来,不忘把坑填上,还会在旁边立个碑,以警后人 —— 能做到这一点的几乎就是伟人了。

分环境

前面提到了你自己开发、给测试小妹妹测试以及给运维人员发布,一共三个环境,而实际上一个软件系统的环境往往不止这些。

常用的环境有:dev、sit、uat、sandbox、pro。

  • dev就是开发环境(Development Environment),每个开发人员自己搭建的环境,当然一般也会在公司内部服务器搭建一些诸如数据库、分布式服务等公用的开发环境服务。

  • sit就是系统集成测试环境(System Integration Testing Environment),主要目的是把系统的各个模块作为一个组进行测试。

  • uat就是用户验收测试环境(User Acceptance Testing Environment),一般是对系统比较熟悉的人,对开发成果进行验收的环境。

  • sandbox就是沙箱环境(Sandbox Environment),这个环境为的是最真实地模拟生产环境。

  • pro就是生产环境(Production Environment),这个环境是我们最终交付的产品所运行的环境。

为什么要有这么多环境呢?答案是形势所迫。随着软件开发的分工日益精细化和软件系统的日益复杂化,不同环境所承担的职责不同,但最终目的是一样的:提高效率、保证质量、节约成本、保证收益。

关于分环境的思想这里就不多讲了,下面要讲的一个问题是分环境是如何实现的?

分环境的实现方式有很多Spring Profile、Spring Boot等等都有不同的实现。

下面讲一个使用 maven profiles 实现分环境配置的方式。

分环境实现

比如我在不同的环境需要提供不同的配置文件,怎么实现呢?

首先在pom.xml增加如下几个环境的配置,并指定配置路径:

<profiles>

    <!-- 分环境profile> -->
    <profile>
        <id>dev</id>
        <!-- 如果dev带上activeByDefault,会默认将dev下的配置复制到config目录下-->
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env>dev</env>
            <package.target>dev</package.target>
            <spring.profiles.active.value>dev</spring.profiles.active.value>
            <yui.skip>true</yui.skip>
            <config.path>src/main/resources/config/dev</config.path>
        </properties>
    </profile>

    <!--sit-->
    <profile>
        <id>sit</id>
        <properties>
            <env>sit</env>
            <package.target>sit</package.target>
            <spring.profiles.active.value>sit</spring.profiles.active.value>
            <yui.skip>false</yui.skip>
            <config.path>src/main/resources/config/sit</config.path>
        </properties>
    </profile>

    <!-- uat -->
    <profile>
        <id>uat</id>
        <properties>
            <env>uat</env>
            <package.target>uat</package.target>
            <spring.profiles.active.value>uat</spring.profiles.active.value>
            <yui.skip>false</yui.skip>
            <config.path>src/main/resources/config/uat</config.path>
        </properties>
    </profile>

    <!--sandbox-->
    <profile>
        <id>sandbox</id>
        <properties>
            <env>sandbox</env>
            <package.target>sandbox</package.target>
            <spring.profiles.active.value>sandbox</spring.profiles.active.value>
            <yui.skip>false</yui.skip>
            <config.path>src/main/resources/config/sandbox</config.path>
        </properties>
    </profile>

    <!--prod-->
    <profile>
        <id>prod</id>
        <properties>
            <env>prod</env>
            <package.target>prod</package.target>
            <spring.profiles.active.value>prod</spring.profiles.active.value>
            <yui.skip>false</yui.skip>
            <config.path>src/main/resources/config/prod</config.path>
        </properties>
    </profile>

</profiles>
复制代码

然后在打包项目的时候通过 -P 参数指定环境就行了。例如打包uat环境:

$ mvn install -Puat
复制代码

指定环境打包的缺点

首先就是慢,也可说浪费咖啡。很多大型项目每次从编译到拉文件都要半个多小时。

那怎么节省发布的时间,让我们早点下班呢?答案就是所有环境一个包。

5个环境就能节省2个小时,太值了!

只打一个包

怎么所有环境一个包呢?

首先在pom.xml配置 maven-resources-plugin 插件,并指定 copy-resources 的路径,把所有环境的配置都打到包里。

<!-- maven-resources-plugin -->
 <plugin>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.6</version>
     <executions>
         <execution>
             <id>copy-resources</id>
             <phase>validate</phase>
             <goals>
                 <goal>copy-resources</goal>
             </goals>
             <configuration>
                 <outputDirectory>${basedir}/target/classes/config</outputDirectory>
                 <resources>
                     <resource>
                         <directory>${config.path}/</directory>
                         <filtering>true</filtering>
                     </resource>
                 </resources>
             </configuration>
         </execution>
     </executions>
 </plugin>
复制代码

然后正常使用 mvn install 打包。

最后把要发布的包复制到指定环境机器的磁盘上以后,通过 mv 命令把需要发布的环境的配置移动出来。例如发布sandbox环境:

mv config/sandbox/* config/
复制代码

当然这个操作不是必须的,比如你在启动容器的时候指定了当前的环境,然后通过 ${spring.profile.active} 来指定当前读取哪个目录下的配置也可以。

版本检查

现在解决了打包慢的问题,但是怎么保证运维人员发布的代码版本跟我们功能所在的版本一致呢?

当然可以口头确认,结果就发生了上面的“惨案”。

那么我们能不能自己检查呢?那就要借助 工具 了。

git-commit-id-plugin

git-commit-id-plugin 是一个插件,会根据当前分支的版本号生成一个 git.properties 文件。

首先在pom.xml引入插件配置:

<!-- https://github.com/git-commit-id/maven-git-commit-id-plugin -->
<plugin>
   <groupId>pl.project13.maven</groupId>
   <artifactId>git-commit-id-plugin</artifactId>
   <version>${git-commit-id-plugin.version}</version>
   <executions>
       <execution>
           <id>get-the-git-infos</id>
           <goals>
               <goal>revision</goal>
           </goals>
       </execution>
   </executions>
   <configuration>
       <!-- 使properties扩展到整个maven bulid 周期, Ref: https://github.com/ktoso/maven-git-commit-id-plugin/issues/280 -->
       <injectAllReactorProjects>true</injectAllReactorProjects>
       <dateFormat>yyyy.MM.dd HH:mm:ss</dateFormat>
       <verbose>true</verbose>
       <!-- 是否生 git.properties 属性文件 -->
       <generateGitPropertiesFile>true</generateGitPropertiesFile>
       <!--git描述配置,可选;由JGit提供实现; -->
       <gitDescribe>
           <!--是否生成描述属性 -->
           <skip>false</skip>
           <!--提交操作未发现tag时,仅打印提交操作ID -->
           <always>false</always>
           <!--提交操作ID显式字符长度,最大值为:40;默认值:7; 0代表特殊意义;-->
           <abbrev>7</abbrev>
           <!--构建触发时,代码有修改时(即"dirty state"),添加指定后缀;默认值:""; -->
           <dirty>-dirty</dirty>
           <forceLongFormat>false</forceLongFormat>
       </gitDescribe>
   </configuration>
</plugin>
复制代码

接着打包项目,你就可以看到自己编译的文件下面多了一个 git.properties 文件:

#Generated by Git-Commit-Id-Plugin
#Sat Apr 20 13:08:01 CST 2019
git.branch=master
git.build.host=DESKTOP-12GT5DQ
git.build.time=2019.04.20 13\:08\:01
git.build.user.email=ijiangtao@foxmail.com
git.build.user.name=ijiangtao
git.build.version=1.1.01.01-SNAPSHOT
git.closest.tag.commit.count=
git.closest.tag.name=
git.commit.id=67b60eeffa9deca877c2b9a28d52a40d3ea55444
git.commit.id.abbrev=67b60ee
git.commit.id.describe=67b60ee
git.commit.id.describe-short=67b60ee
git.commit.message.full=\u53D1\u9001\u91CD\u8981\u6570\u636E\u7ED9\u8001\u677F~~~~
git.commit.message.short=\u53D1\u9001\u91CD\u8981\u6570\u636E\u7ED9\u8001\u677F~~~~
git.commit.time=2019.04.20 12\:57\:50
git.commit.user.email=ijiangtao@foxmail.com
git.commit.user.name=ijiangtao
git.dirty=false
git.remote.origin.url=https\://github.com/javastudydemo/jsd-maven.git
git.tags=
git.total.commit.count=2
复制代码

有了这个文件,我们就可以清晰地知道生产环境的代码是什么版本了。

需要特别注意的是,使用这个插件要保证你编译的项目是有.git目录的,因为这个插件要获取git的提交信息,如果不使用git进行版本管理的项目,编译会报错。

版本检查地址

下面提供一个Controller来展示git的提交信息。

package net.ijiangtao.tech.maven.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;

/**
 * @author ijiangtao
 */
@Controller
@Api(value = "", description = "git info from git-commit-id-plugin")
public class GitCommitController {

    /**
     * @return
     */
    @RequestMapping("/git/commit/info")
    @ResponseBody
    @ApiOperation(value = "get commit info", httpMethod = "GET")
    public String showGitCommitInfo() {
        //git.properties
        ResourceBundle resourceBundle = ResourceBundle.getBundle("git", defaultIfNull(null, Locale.getDefault()));

        Map<String, String> map = new TreeMap<>();

        Enumeration<String> keysEnumeration = resourceBundle.getKeys();

        while (keysEnumeration.hasMoreElements()) {
            String key = keysEnumeration.nextElement();

            map.put(key, resourceBundle.getString(key));
        }

        return JSON.toJSONString(map, SerializerFeature.PrettyFormat);
    }

    /**
     * @return
     */
    @ApiOperation(value = "get commit id", httpMethod = "GET")
    @RequestMapping("/git/commit/id")
    @ResponseBody
    public String showGitCommitId() {
        //git.properties
        ResourceBundle resourceBundle = ResourceBundle.getBundle("git", defaultIfNull(null, Locale.getDefault()));
        return resourceBundle.getString("git.commit.id");
    }


}
复制代码

通过Jetty插件启动项目,并访问 SwaggerUI 地址 http://localhost:8241/swagger/index.html ,最后通过 http://localhost:8241/git/commit/info 请求到了我们的git提交信息。

DevOps: 使用Maven插件实现分环境配置和版本检查

一般我们为了版本回滚的方便,发布的时候会通过git commit id进行打包,可以通过机器对比两者是否一致,达到自动检查的目的,而不是每次需要人工检查。


以上所述就是小编给大家介绍的《DevOps: 使用Maven插件实现分环境配置和版本检查》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Sovereign Individual

The Sovereign Individual

James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00

Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试