1.文档地址:spring alibaba nacos discovery example
2.创建一个spring boot项目
3.添加nacos discovery依赖
<dependencies><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!-- web启动 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>2.1.2.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
添加配置
##### properties
spring.application.name=producer-server
server.port=10881
##### yaml
discovery:server-addr: localhost:8848
在代码中添加@EnableDiscoveryClient
@SpringBootApplication
@NacosPropertySource(dataId = "user-producer",autoRefreshed = true)
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);System.out.println("启动成功");}
}
启动服务就可以在nacos 上看到发布的服务。
总结:在引用jar的时候由于spring-boot 版本号是2.1.2.RELEASE,spring-cloud-alibaba版本号是2.2.2.RELEASE时 导致服务启动失败。将spring-cloud-alibaba版本号改为2.1.2.RELEASE 可以正常启动。当启动后发现服务没有注册。检查注解是否加上,nacos注册地址是否加上,服务名称是否加上。