我有一个spring boot Web应用程序,它只打印一个在Kubernetes的ConfigMap中传递的属性。
这是我的主要课程:
@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
部署kubecetl 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中定义的值。
示例项目也包含https://drive.google.com/open?id=107IcwnYIbVpmwVgdgi8Dhx4nHEFAVxV8上可用的yaml文件和Docker文件。
还检查了启动DEBUG日志,但没有看到任何错误或线索为什么它不起作用。
答案 0 :(得分:1)
Spring Cloud Kubernetes documentation不完整。它缺少包含此依赖项以启用从ConfigMap加载应用程序属性的说明:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-config</artifactId>
</dependency>
答案 1 :(得分:0)
您很亲密:
1)稍微定义ConfigMap,以便它包含属性文件。例如:
apiVersion: v1
kind: ConfigMap
metadata:
name: demo
data:
demo.properties: |
bean.message: This is an info from k8
2)将ConfigMap挂载为卷:
...
spec:
containers:
- name: demo
...
volumeMounts:
- name: config
mountPath: /demo/config
volumes:
- name: config
configMap:
name: demo
结果,在ConfigMap中定义的demo.properties
文件将“出现”在运行容器的/demo/config
目录中。
3)在@PropertySource
类中添加MyConfig
注释:
@Configuration
@PropertySource("file:/demo/config/demo.properties")
@ConfigurationProperties(prefix = "bean")
public class MyConfig {
...
}