在某些CI,CD平台部署服务上线后,我们往往难以获取当前部署应用的git版本,或由于时间、文档缺失难以获知当前上线版本,为此我们可以在应用中添加查询git版本接口。
以下实现方式以 gradle+ spring boot为例
在jar包中添加git info文件
首先在gradle中添加task,在代码库resource目录下生成git.properties文件
buildscript {
dependencies {
classpath("org.ajoberstar:grgit:1.1.0")
}
}
task injectGitInfo {
def gitRepo = org.ajoberstar.grgit.Grgit.open(project.file('.'))
def propertyFile = file 'src/main/resources/git.properties'
propertyFile.deleteOnExit()
propertyFile.createNewFile()
def props = new Properties()
def map = ["git.branch" : gitRepo.branch.current.name
, "git.commitId" : gitRepo.head().id
, "git.commitAbbrevId" : gitRepo.head().abbreviatedId
, "git.commitUserName" : gitRepo.head().author.name
, "git.commitUserEmail": gitRepo.head().author.email
, "git.commitMessage" : gitRepo.head().fullMessage
, "git.commitTime" : gitRepo.head().time.toString()]
props.putAll(map)
props.store(propertyFile.newOutputStream(), "add git info")
}
为了在每次build jar的时候自动执行该任务,我们还需要添加
build.dependsOn injectGitInfo
增加git查询接口
首先利用Spring ConfigurationProperties注解读取git.properties
@Component
@PropertySource("classpath:git.properties")
@ConfigurationProperties("git")
@Data
public class GitCommitInfo {
private String commitId;
private String commitAbbrevId;
private String commitTime;
private String commitUserName;
private String branch;
private String commitUserEmail;
private String commitMessage;
}
增加git查询接口
@RestController
public class GitCommitInfoController {
@Autowired
private GitCommitInfo gitCommitInfo;
@GetMapping("/git_info")
public GitCommitInfo getGitCommitInfo() {
return gitCommitInfo;
}
}
验证接口
curl http://localhost:8001/git_info
{
"commitId": "72fe61581be54cf300aa0d8ea3b1ca65e0cbdb08",
"commitAbbrevId": "72fe61",
"commitTime": "1533721585",
"commitUserName": "Huang Yan",
"branch": "master",
"commitUserEmail": "huangydyn@gmail.com",
"commitMessage": "[Tech] implement git commit api"
}