• SpringBoot使用git-commit-id-maven-plugin打包


    简介

    git-commit-id-maven-plugin 是一个maven 插件,用来在打包的时候将git-commit 信息打进jar中。

    这样做的好处是可以将发布的某版本和对应的代码关联起来,方便查阅和线上项目的维护。至于它的作用,用官方说法,这个功能对于大型分布式项目来说是无价的。

    功能

    你是否经常遇到这样的问题:

    • 测试提交了一个bug,开发人员无法确认是哪个版本有这个问题,当前测试环境部署的是某个版本吗?生产环境会不会也有这个问题?

    • 公司内部的项目,总共几十、几百个服务,每天都有服务的生产环境部署,一个服务甚至一天上线好几次,对于项目管理来说无法清晰了解某一时刻某个服务的版本

    • 如何验证我的代码是否已经上线?

    • 。。。。。。

    以上种种,都有一个共同的诉求,就是我希望在打包的时候将最后一次 git commit id 和当前 jar 关联起来并可试试查询jar对应的git commit id 。

    实践

    引入插件

    本例SpringBoot版本为 2.7.6,java版本为11

    此插件已经上传到中央仓库(https://central.sonatype.com/artifact/io.github.git-commit-id/git-commit-id-maven-plugin?smo=true)

    在项目pom.xml 中引入如下插件

    
    
    <project>
        ......
        <build>
            <plugins>
                
                <plugin>
                    <groupId>io.github.git-commit-idgroupId>
                    <artifactId>git-commit-id-maven-pluginartifactId>
                    <version>5.0.0version>
                    <executions>
                        <execution>
                            <id>get-the-git-infosid>
                            <goals>
                                <goal>revisiongoal>
                            goals>
                            <phase>initializephase>
                        execution>
                    executions>
                    <configuration>
                        <generateGitPropertiesFile>truegenerateGitPropertiesFile>
                        <generateGitPropertiesFilename>${project.build.outputDirectory}/git.generateGitPropertiesFilename>
                        <includeOnlyProperties>
                            <includeOnlyProperty>^git.build.(time|version)$includeOnlyProperty>
                            <includeOnlyProperty>^git.commit.id.(abbrev|full)$includeOnlyProperty>
                        includeOnlyProperties>
                        <format>txtformat>
                        <commitIdGenerationMode>fullcommitIdGenerationMode>
                    configuration>
                plugin>
            plugins>
        build>
    project>
    
    
    
    
    • generateGitPropertiesFilename:用于指定生成的gitCommitInfo存放到哪个位置,后缀可以任意指定,如果不指定将使用format的值
    • format:指定文件后缀,一般为 properties , json
    • commitIdGenerationMode:记录完整信息,若format为json,此值必须为full

    此外为了能成功打出jar包,还需要如下插件的配合:

    
    
    <plugin>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-maven-pluginartifactId>
        <version>${spring-boot.version}version>
        <configuration>
            <includeSystemScope>trueincludeSystemScope>
            <excludes>
                <exclude>
                    <groupId>org.projectlombokgroupId>
                    <artifactId>lombokartifactId>
                exclude>
            excludes>
        configuration>
        <executions>
            <execution>
                <id>repackageid>
                <goals>
                    <goal>repackagegoal>
                goals>
            execution>
        executions>
    plugin>
    
    
    

    使用maven执行 clean and package ,将在target\classes下生成 git.json文件,内容如下:

    
    #Generated by Git-Commit-Id-Plugin
    git.build.time=2024-02-21T10\:41\:24+0800
    git.build.version=0.0.1-SNAPSHOT
    git.commit.id.abbrev=3fc9c80
    git.commit.id.full=3fc9c8009a48e22ef171c98a97398005e9f30a4a
    
    

    同时,如果我们反编译生成的jar包,将在BOOT-INF/classes下看到git.json 文件

    GitCommitIdMavenPlugin插件有丰富的配置选项,更多配置参考:

    
    
    <configuration>
        
        <dotGitDirectory>${project.basedir}/.gitdotGitDirectory>
        
        <prefix>gitprefix>
        
        
        <dateFormat>yyyy-MM-dd'T'HH:mm:ssZdateFormat>
        
        
        <dateFormatTimeZone>${user.timezone}dateFormatTimeZone>
        
        <verbose>falseverbose>
        
        <generateGitPropertiesFile>truegenerateGitPropertiesFile>
        
        <generateGitPropertiesFilename>${project.build.outputDirectory}/git.propertiesgenerateGitPropertiesFilename>
        
        <format>propertiesformat>
        
        <skipPoms>trueskipPoms>
        
        
        <injectAllReactorProjects>falseinjectAllReactorProjects>
        
        
        <failOnNoGitDirectory>truefailOnNoGitDirectory>
        
        
        <failOnUnableToExtractRepoInfo>truefailOnUnableToExtractRepoInfo>
        
        
        <skip>falseskip>
        
        
        <offline>falseoffline>
        
        
        <runOnlyOnce>falserunOnlyOnce>
        
        
        <excludeProperties>
            
        excludeProperties>
        
        
        <includeOnlyProperties>
            
        includeOnlyProperties>
        
        
        <replacementProperties>
            
        replacementProperties>
        
        
        <useNativeGit>falseuseNativeGit>
        
        
        <nativeGitTimeoutInMs>30000nativeGitTimeoutInMs>
        
        
        <abbrevLength>7abbrevLength>
        
        
        <commitIdGenerationMode>flatcommitIdGenerationMode>
        
        
        <gitDescribe>
            
            <skip>falseskip>
            
            <always>truealways>
            
            <abbrev>7abbrev>
            
            <dirty>-dirtydirty>
            
            <match>*match>
            
            <tags>falsetags>
            
            <forceLongFormat>falseforceLongFormat>
        gitDescribe>
        
        
        <validationProperties>
            <validationProperty>
                
                <name>validating project versionname>
                
                <value>${project.version}value>
                
                <shouldMatchTo>shouldMatchTo>
            validationProperty>
            
        validationProperties>
        
        
        <validationShouldFailIfNoMatch>truevalidationShouldFailIfNoMatch>
        
        
        <evaluateOnCommit>HEADevaluateOnCommit>
        
        
               useBranchNameFromBuildEnvironment>trueuseBranchNameFromBuildEnvironment>
    
    
    
    <injectIntoSysProperties>trueinjectIntoSysProperties>
    configuration>
    
    
    
    

    查询gitCommitInfo

    通过编写一个接口,用来查询生成的GitCommitInfo,核心代码如下:

    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.util.ResourceUtils;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import java.io.*;
    
    @Slf4j
    @RestController
    @RequestMapping("/version")
    public class VersionController {
    
        /**
         * 获取 git.json 中的内容
         * @return
         * @throws IOException
         */
        @GetMapping("/gitCommitId")
        public String getGitCommitId() throws IOException {
            //git.json  or  git.properties
            Resource resource = new DefaultResourceLoader().getResource("classpath:git.json");
            if (resource.exists()) {
                InputStream inputStream = resource.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                StringBuffer content = new StringBuffer();
                String s = "";
                while ((s = reader.readLine()) != null) {
                    content = content.append(s);
                }
                return content.toString();
            } else {
                return "";
            }
        }
    }
    
     
    

    兼容性

    与java的兼容性

    • java8:插件版本=4.x
    • java11:插件版本>=5

    与maven的兼容性

    • maven3:插件版本=4.x
    • maven3.2.x:插件版本>=7

    引用

  • 相关阅读:
    【安全】对称加密、非对称加密、数字签名和CA是什么?
    [SQL-SERVER:数据库安全及维护]:MSSM工具进行附加还原备份等操作
    NISP网络信息安全面试怎么选择(六)NISP管理中心
    自动化测试-Xpath
    FDbus NDK以及QNX交叉编译
    stm32学习笔记:GPIO输入
    C语言 ——深入理解指针(2)
    JuiceFS 在多云存储架构中的应用 | 深势科技分享
    英伟达GPU架构加速狂飙
    华为机试真题 Java 实现【查找众数及中位数】
  • 原文地址:https://www.cnblogs.com/Naylor/p/18024689