版本和依赖
SpringBoot、SpringCloud Alibaba、OpenFeign等存在版本对应关系,版本不匹配可能会出现问题。以如下以来的版本为例说明如何接入Nacos
<dependencies> <dependency> <!--配置中心依赖--> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <exclusions> <exclusion> <groupId>com.alibaba.nacos</groupId> <artifactId>nacos-client</artifactId> </exclusion> </exclusions> </dependency> <!--客户端版本依赖--> <dependency> <groupId>com.alibaba.nacos</groupId> <artifactId>nacos-client</artifactId> <version>2.1.0</version> </dependency> <!--注册中心版本依赖--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> <version>3.0.6</version> </dependency> </dependencies> |
接入注册中心
服务注册
接入注册中需要的增加的依赖是spring-cloud-starter-alibaba-nacos-discovery,在第二节中已经给出。
注意: 实例中SpringBoot 2.6.1 SpringCloud版本为2021.0.4.0,这两个版本需要匹配。如果使用其他版本,可以从Spring Cloud 官方查询匹配版本。
在本地创建服务提供者应用工程,然后添加依赖,并开启服务注册与发现功能,并将注册中心指定为Nacos Server。 接入注册中心需要在配置文件中增加相关配置,以yml文件为例,可以加在application-prod.yml中增加如下配置文件:
spring: cloud: nacos: discovery: username: ${_NAOCS_USERNAME} password: ${_NAOCS_PASSWORD} server-addr: ${_NACOS_SERVER_ADDRESS} namespace: ${_NACOS_NAMING_NAMESPACE} group: ${_NACOS_NAMING_GROUP} |
以上配置中变量的实际值,可以通过环境变量的方式提供。环境变量可以在云容器引擎中配置。
除修改配置文件以外,需要在Spring Boot 项目的启动类上增加@EnableDiscoveryClient注解。如下列代码所示:
@EnableDiscoveryClient
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
修改配置文件后启动应用。启动成功后可以在控制台页面或者通过OpenAPI查看当前注册的服务。
返回当前命名空间的服务数据
{ "count": 1, "serviceList": [ { "name": "demo-test", "groupName": "paas-default", "clusterCount": 1, "ipCount": 1, "healthyInstanceCount": 1, "triggerFlag": "false" } ] } |
通过OPENAPI查询服务的详情,包含注册服务的具体信息。
{ "list": [ { "ip": "10.10.133.101", "port": 20080, "weight": 1.0, "healthy": true, "enabled": true, "ephemeral": true, "clusterName": "DEFAULT", "serviceName": "paas-default@@demo-test", "metadata": { "preserved.register.source": "SPRING_CLOUD" }, "instanceHeartBeatInterval": 5000, "instanceHeartBeatTimeOut": 15000, "ipDeleteTimeout": 30000 } ], "count": 1 } |
服务发现
除了服务注册以外,注册中心也提供服务发现的功能。Nacos服务发现可以使用RestTemplate和FeignClient两个客户端来调用注册的服务。如下以使用FeignClient调用为例:
(1) 调用方增加依赖
<dependency> |
(2) 在 Spring Boot 项目的启动文件上添加 @EnableFeignClients 注解,开启 OpenFeign,具体实现代码如下图:
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
(3)最重要的一步,创建OpenFeign与服务提供者的调用接口,具体实现代码如下图:
示例这里调用的是自己的接口。
@FeignClient(name = "demo-test")
public interface OrderFeignService {
@GetMapping("/call/{name}")
String call(@PathVariable(value = "name") String name);
}
(4)然后在controller中访问接口,就可以获得通过feign请求的的结果。
@RestController
@RequestMapping("feign")
public class DiscoverController {
@Resource
private IFeignClientService iFeignClientService;
@GetMapping("/echo/{message}")
public String getMessage(@PathVariable String message) {
return iFeignClientService.call(message);
}
}
(5)最后请求feign/echo/{message}接口即可通过feign调call接口了。
至此通过FeignClient调用服务接口的流程就实现了。
接入配置中心
接入配置中需要的增加的依赖是spring-cloud-starter-alibaba-nacos-config,在第二节中已经给出。
接入配置中心需要在配置文件中增加相关配置,以yml文件为例,需要在bootstrap.yml中增加如下配置信息:
spring: cloud: nacos: # config center config: username: ${_NAOCS_USERNAME} password: ${_NAOCS_PASSWORD} server-addr: ${_NACOS_SERVER_ADDRESS} namespace: ${_NACOS_CONFIG_NAMESPACE} group: ${_NACOS_CONFIG_GROUP} prefix: |
其中 namespace 默认值为空,也就是public命名空间,group 默认值为DEFAULT_GROUP, prefix属性为非必要属性,可以按照需要决定是否配置。配置文件中的值既可以配置真实值,也可以配置为从环境变量中获取。
为了方便获取和使用配置,可以自定义配置类。在自定义属性类上需要增加注解,否则远程配置更新是客户端的配置不会自动更新。如下所示,定义了一个前缀为user的属性类,自动绑定user前缀的属性
@RefreshScope @ConfigurationProperties(prefix = "user") public class User implements InitializingBean, DisposableBean { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } |
配置完成后,启动应用。在启动应用后查看启动日志,会发现在一般情况下,应用监听三个配置文件而不论这三个远程配置文件是否存在。
[fixed-prod-IP_47588] [subscribe] +paas-default+prod [fixed-prod-IP_47588] [add-listener] ok, tenant=prod, dataId=, group=paas-default, cnt=1 [Nacos Config] Listening config: dataId=, group=paas-default [fixed-prod-IP_47588] [subscribe] -prod.properties+paas-default+prod [fixed-prod-IP_47588] [add-listener] ok, tenant=prod, dataId=-prod.properties, group=paas-default, cnt=1 [Nacos Config] Listening config: dataId=-prod.properties, group=paas-default [fixed-prod-IP_47588] [subscribe] .properties+paas-default+prod [fixed-prod-IP_47588] [add-listener] ok, tenant=prod, dataId=.properties, group=paas-default, cnt=1 [Nacos Config] Listening config: dataId=.properties, group=paas-default |
默认情况下,监听的配置文件的dataId={prefix}-prefix−{spring.profile.active}.${file-extension}
其中profix默认为${spring.application.name}
file-extension表示配置的类型,默认为properties。
如果没有指定spring.profile.active,那么dataId就变成了profix.{profix}.profix.{file-extension}
启动时会发现启动日志中会打出多个,
(1)${prefix}
(2)${prefix}−{spring.profile.active}
(3)${prefix}−{spring.profile.active}.${file-extension}。
说明其实是可以匹配配置中心中配置的多条配置名称。匹配优先级是:3>2>1,精确匹配。
通过 控制台或者是OPENAPI更新配置,在应用端可以接收到更新的推送。如果服务端同时存在多个监听的配置,则当更新高优先级的配置时,客户端才会接收到更新。
例如:
客户端接收到更新推送,变更为最新的值。至此,说明接入配置中心成功,配置可以动态更新了。