操作场景
本文档主要介绍在弹性微服务控制台中实现 SpringCloud 应用服务注册与发现的具体步骤。
操作步骤
控制台操作
1. 登录 弹性微服务控制台。
2. 在左侧导航栏,单击应用管理进入应用管理页面,选择您的应用部署地域。
3. 单击新建,进入新建应用页面,填写应用信息并部署。参考 创建并部署应用。
4. 对于 Spring Cloud 应用,如果所选择的发布环境中关联了注册中心,在部署时可以选择自动注入注册中心信息。n
具体配置
如果选择了自动注入注册中心,在用户提交部署时,弹性微服务会自动把注册中心默认参数以 properties 文件形式,保存到环境中名为
tse-config
的 ConfigMap 中,并通过 VolumeMounts 的形式,挂载到应用的 /config/tse-default-spring-cloud-config.properties
目录下。同时,弹性微服务会为将此目录添加到应用的 SPRING_CONFIG_ADDITIONAL-LOCATION 环境变量中,如果应用中不存在 SPRING_CONFIG_ADDITIONAL-LOCATION,则将会为应用添加此环境变量。
基本配置如下所示:
apiVersion: v1kind: Deploymentmetadata:name: my-servicespec:containers:- name: my-serviceimage: my-imageenv:- name: SPRING_CONFIG_ADDITIONAL-LOCATIONvalue: file:/config/tse-default-spring-cloud-config.propertiesvolumeMounts:- name: tse-configmountPath: /config/tse-default-spring-cloud-config.propertiessubPath: tse-default-spring-cloud-config.propertiesvolumes:- name: tse-configconfigMap:name: tse-configitems:- key: tse-default-spring-cloud-config.propertiespath: tse-default-spring-cloud-config.properties
对于不同的注册中心,弹性微服务会注入不同的参数:
假设申请的 zookeeper 地址为:10.0.1.30:2181。
apiVersion: v1data:tse-default-spring-cloud-config.properties: |spring.cloud.zookeeper.connectString=10.0.1.30:2181spring.cloud.zookeeper.discovery.preferIpAddress=truekind: ConfigMapmetadata:name: tse-config
假设申请的 nacos 地址为:10.0.120.11:8848。
apiVersion: v1data:tse-default-spring-cloud-config.properties: |spring.cloud.nacos.discovery.server-addr=10.0.120.11:8848kind: ConfigMapmetadata:name: tse-config
说明与注意
关于 preferIpAddress
这里所有注入的注册中心参数都加上了 xxx.preferIpAddress=true,因为 Spring Cloud 在获取到本机IP时(弹性微服务中是 Pod IP)会自动再根据 IP 反查域名,如果判断 preferIpAddress 是 false(默认为 false),则通过域名去注册,否则通过 IP 去注册。
在弹性微服务中 Pod IP 映射的是 PodName,也就是如果不设置 preferIpAddress=true,则注册到注册中心的地址为 PodName,其他服务从注册中心拉取的服务实例地址为 PodName,导致通过 PodName 访问实例不通。
关于 Spring boot additional location
弹性微服务自动添加的环境变量 SPRING_CONFIG_ADDITIONAL-LOCATION 为 Spring boot 应用提供在应用外定制化 config 的能力,但此参数只在 Spring boot 2.0 版本之后生效。
如果您使用的是 Spring boot 1.x 版本,请将挂载目录
/config/tse-default-spring-cloud-config.properties
自行添加到 SPRING_CONFIG_LOCATION 环境变量中。您也可以直接添加 JVM 启动参数进行设置,具体设置如下:
# 假设申请的 zookeeper 地址为:10.0.1.30:2181-Dspring.cloud.zookeeper.connectString=10.0.1.30:2181-Dspring.cloud.zookeeper.discovery.preferIpAddress=true
# 假设申请的nacos地址为:10.0.120.11:8848-Dspring.cloud.nacos.discovery.server-addr=10.0.120.11:8848