注意:由于时间关系,所以系列教程以demo为主。。。。
基础框架搭建
以idea为开发工具,构建多项目结构开发(grails4多项目构建可以参考后面的博客传送门),具体结构如下图:
在主build.gradle中引入基础组件(Spring cloud Alibaba)
这里需要注意版本的对照关系
Spring Cloud Version | Spring Cloud Alibaba Version | Spring Boot Version |
-------- | -------- | -------- |
Spring Cloud Greenwich | 2.1.x.RELEASE | 2.1.x.RELEASE |
Spring Cloud Finchley | 2.0.x.RELEASE | 2.0.x.RELEASE |
Spring Cloud Edgware | 1.5.x.RELEASE | 1.5.x.RELEASE |
由于我们使用的是最新的Grails4.0.2版本做演示,所以我们引入:2.1.x版本的spring cloud alibaba
dependencyManagement {
dependencies {
dependency group: 'com.alibaba.cloud', name: 'spring-cloud-alibaba-dependencies', version: '2.1.1.RELEASE', ext: 'pom'
}
}
下面我们引入nacos,在需要的服务中添加对应的包
// https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-alibaba-nacos-discovery
compile group: 'com.alibaba.cloud', name: 'spring-cloud-alibaba-nacos-discovery', version: '2.1.1.RELEASE'
集成Nacos注册中心
- 引入
spring-cloud-starter-alibaba-nacos-discovery
,上一步骤已完成; - 修改配置文件
application.yml
,配置 nacos 的服务地址(注意修改服务端口);
server:
port: 8030
---
spring:
application:
name: core-service
cloud:
nacos:
discovery:
enabled: true
server-addr: 127.0.0.1:8848
service: ${spring.application.name}
- 在项目启动类上添加
@EnableDiscoveryClient
注解
import org.springframework.cloud.client.discovery.EnableDiscoveryClient
@PluginSource
@EnableDiscoveryClient
class Application extends GrailsAutoConfiguration {
static void main(String[] args) {
GrailsApp.run(Application, args)
}
}
- 启动测试,正常启动,并发现已经注册
- 如果出现下面报错,则查看引用的nacos版本是否正确(非start版本)
Description:
Application failed to connect to Nacos server: ""
Action:
Please check your Nacos server config
Process finished with exit code -1