我是一个能够打印从Kubernetes的ConfigMap中传递的属性的Spring Boot Web应用程序。
这是我的主类:
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class DemoApplication {
private MyConfig config;
private DiscoveryClient discoveryClient;
@Autowired
public DemoApplication(MyConfig config, DiscoveryClient discoveryClient) {
this.config = config;
this.discoveryClient = discoveryClient;
}
@RequestMapping("/")
public String info() {
return config.getMessage();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping("/services")
public String services() {
StringBuilder b = new StringBuilder();
discoveryClient.getServices().forEach((s) -> b.append(s).append(" , "));
return b.toString();
}
}
而MyConfig
类如下:
@Configuration
@ConfigurationProperties(prefix = "bean")
public class MyConfig {
private String message = "a message that can be changed live";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
基本上,调用根资源时我总是会得到以下消息:
而调用/services时,我实际上会得到一个Kubernetes服务列表。可以实时更改的消息
我使用
kubectl create -f configmap-demo.yml
命令创建ConfigMap,其内容如下:apiVersion: v1
kind: ConfigMap
metadata:
name: demo
data:
bean.message: This is an info from k8
使用kubectl create -f deploy-demo.yml
进行部署,内容如下:
apiVersion: apps/v1
kind: Deployment
metadata:
name: demo
labels:
app: demo
spec:
replicas: 1
selector:
matchLabels:
app: demo
template:
metadata:
labels:
app: demo
spec:
# this service account was created according to
# https://kubernetes.io/docs/reference/access-authn-authz/rbac/#service-account-permissions
# point 5 - Grant super-user access to all service accounts cluster-wide (strongly discouraged)
serviceAccountName: i18n-spring-k8
containers:
- name: demo
image: aribeiro/sck-demo
imagePullPolicy: Never
env:
- name: JAVA_OPTS
value:
ports:
- containerPort: 8080
volumes:
- name: demo
configMap:
name: demo
问题在于访问根资源
/
时,我总是得到默认的硬编码值,而不是Kubernetes' ConfigMap中定义的值。示例项目还提供了yaml文件和Docker文件,可从https://drive.google.com/open?id=107IcwnYIbVpmwVgdgi8Dhx4nHEFAVxV8获取。
同时,我也检查了启动调试日志,未发现任何错误或线索说明为什么它不起作用。