公司的運(yùn)行環(huán)境有點(diǎn)神奇,有時(shí)K8S的集群在生產(chǎn)環(huán)境會(huì)被人復(fù)制一份,成為一個(gè)新集群在跑,而且我們還不知道他們什么時(shí)候會(huì)做這件事。于是有可能,我們上了新版本,被復(fù)制的集群在跑舊版本。
怎么辦呢?小弟突發(fā)奇想:能不能把我們期望運(yùn)行的版本號(hào)放在Redis里,然后本應(yīng)用啟動(dòng)的時(shí)候看看版本對(duì)不對(duì),版本不對(duì)就不提供服務(wù)。
這個(gè)方案未必適合。但是我也想看看能不能取得應(yīng)用的版本號(hào)。
查看了一下Spring Boot打出來(lái)的包,找到一個(gè) "META-INF/MANIFEST.MF", 竟然很神奇地有我想要的信息。
Implementation-Title: demo
Implementation-Version: 0.0.1-SNAPSHOT
那最簡(jiǎn)單的做法就是讀這個(gè)文件并把結(jié)果拿出來(lái)!
上代碼:
package cn.gzten.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@RestController
public class TestController {
@GetMapping("/")
public String getVersion() {
try(InputStream ins = ClassLoader.getSystemResourceAsStream("META-INF/MANIFEST.MF")) {
Properties prop = new Properties();
prop.load(ins);
String appName = prop.getProperty("Implementation-Title");
String appVersion = prop.getProperty("Implementation-Version");
return String.join("-", appName, appVersion);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
結(jié)果不錯(cuò):
$ curl -i http://localhost:8080
HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
Content-Length: 19
demo-0.0.1-SNAPSHOT