最近开发了一个 SpringBoot 项目,需要将其发布为一个微服务,注册到 Nacos,参考 Nacos 官网文档的说明没有搞定,各种问题,最后还是使用了 SpringCloud 的依赖才成功的,下面介绍下 SpringBoot 注册到 Nacos 的过程。
如果想要不使用 SpringCloud 依赖直接将 SpringBoot 项目注册到 Nacos,可以参考这篇文章:
SpringBoot使用Nacos进行服务注册发现与配置管理
1. 环境介绍
当前使用的 Nacos 版本为 2.0.2,三个实例,集群部署。
本来使用的 SpringBoot 版本为 2.6.2,为了使用 Nacos,降到了 2.3.4.RELEASE。因为 SpringBoot 2.4.0 版本之后删掉了ConfigurationBeanFactoryMetadata
,而 Nacos 需要用到这个,所以会报如下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nacosConfigurationPropertiesBinder': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
我的 SpringBoot 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
或者使用2.4.0
版本之前的最新版本2.3.12.RELEASE
:
2. 配置过程
一个普通的 SpringBoot 项目,首先需要在 pom.xml 中添加依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
项目启动类上需要添加注解:
import org.springframework.cloud.client.discovery.EnableDiscoveryClient
...
@EnableDiscoveryClient
接下来需要修改配置文件,添加下面三项配置:
#服务名
spring.application.name=output-server-test
#Nacos服务地址
spring.cloud.nacos.discovery.server-addr=192.168.0.10:30000
#Nacos命名空间,注意要和网关服务gateway在同一个命名空间下
spring.cloud.nacos.discovery.namespace=gtcom-console
项目启动成功后,就可以在 Nacos 的服务管理
中的服务列表
中的对应命名空间下看到注册成功的服务了。
3. 网关配置
想要让其他服务通过网关能成功调用该服务,还需要在网关服务的配置文件中添加对应的路由,比如我这个项目的所有接口地址前缀是/output
:
server.servlet.context-path=/output
这时需要在网关服务的配置文件中添加:
spring:
cloud:
gateway:
routes:
#输出服务
- id: output-server-test
uri: lb://output-server-test
predicates:
- Path=/output/**