首先申明:本文档主要记录了自己使用Gradle如何构建项目,仅供参考!
环境准备
为了方便,项目中作为注册中心和配置中心的Nacos、数据库Mysql都使用docker来安装
安装Nacos
参照官方文档:nacos.io/docs/latest…
按照官方文档,先生成长度大于32字符的字符串,然后对其进行Base64编码,得到的值作为NACOS_AUTH_TOKEN的值
使用到的工具如下:
- 生成64位长度的随机字符串 www.jyshare.com/compile/9/
- 将生成的字符串进行Base64编码www.jyshare.com/front-end/1…
- 完善官方文档的docker命令
docker run --name nacos -e MODE=standalone -e NACOS_AUTH_TOKEN=Z0o4ZEQ5ZUczdlg0YUQzeFI0bEQ3b0MwaUQwbFkyZFY5YVE5dlE4eUE2a0owd0w1b0w0dUw2eEI3cVg2eVQ5Zw== -e NACOS_AUTH_IDENTITY_KEY=naik -e NACOS_AUTH_IDENTITY_VALUE=naiv -p 8080:8080 -p 8848:8848 -p 9848:9848 -d nacos/nacos-server:latest
- 访问nacos控制台:http://127.0.0.1:8080/index.html
点击确认后,再次输入:用户名/密码(nacos/nacos),即可进入
安装Mysql(可选)
直接执行如下指令(密码可自行调整)
docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_CHARACTER_SET_SERVER=utf8mb4 -e MYSQL_COLLATION_SERVER=utf8mb4_unicode_ci -v /docker/mysql/data:/var/lib/mysql --restart=always mysql:8.0.36
测试连接
至此,项目中需要的Nacos和Mysql就安装好了
创建项目
父项目
- 使用idea创建一个空的Gradle项目作为父项目
打开项目如下
- 完善父项目的build.gradle配置
// 构建脚本自身的配置
buildscript {
// 定义全局版本常量(对应Maven的properties标签)
ext {
springBootVersion = "2.7.14" // springBoot版本
springCloudVersion = "2021.0.8" // springCloud版本
springCloudAlibabaVersion = "2021.0.5.0" // springCloudAlibaba版本
}
// 声明构建脚本的下载仓库(对应Maven的pluginRepositories标签)
repositories {
mavenLocal() // 优先从本地仓库找插件
mavenCentral()
maven {url "https://maven.aliyun.com/repository/public"} // 阿里云公共仓库
}
// 引入构建过程中需要的插件(对应Maven的build/plugins/plugin)
dependencies {
// 把springboot插件加到构建脚本的classpath中,用于构建和执行jar(仅用在启动模块)
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
}
}
// 每个子模块应用的公共配置
subprojects {
apply plugin: "java" // java编译插件(所有子模块都需要)
apply plugin: "io.spring.dependency-management" // 依赖管理插件(管控版本)
group = "com.chaoup" // 组织id(对应maven的groupId)
version = "1.0.0-SNAPSHOT" // 版本号
sourceCompatibility = "17" // 使用java17
targetCompatibility = "17" // 目标编译版本,与resource一致
// 声明项目依赖的仓库(对应maven的repositories标签)
repositories {
mavenLocal() // 优先从本地仓库找插件
mavenCentral()
maven {url "https://maven.aliyun.com/repository/public"} // 阿里云公共仓库
}
// 依赖管理:导入BOM管控所有子模块的依赖版本(仅管控版本,不引入依赖)
dependencyManagement {
imports {
mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}"
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "com.alibaba.cloud:spring-cloud-alibaba-dependencies:${springCloudAlibabaVersion}"
}
}
// 通用依赖(所有子模块可继承,仅声明必要的通用依赖)
// maven中的groupId artifactId version 在gradle中用groupId:artifactId:version表示
dependencies {
compileOnly "org.projectlombok:lombok"
annotationProcessor "org.projectlombok:lombok"
testImplementation "org.springframework.boot:spring-boot-starter-test"
}
test {
useJUnitPlatform()
}
}
- 删除父项目的src目录
服务提供者
- 使用idea创建一个服务提供者Server-provider
- 完善服务提供者Server-provider的build.gradle配置
apply plugin:"org.springframework.boot" // 应用spring boot 插件
dependencies {
implementation "org.springframework.boot:spring-boot-starter-web" // spring boot web 核心依赖
implementation "com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery" // nacos服务发现
implementation "com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config" // nacos配置中心
implementation "org.springframework.cloud:spring-cloud-starter-bootstrap" // 启用bootstrap上下文,让bootstrap.yml文件中的nacos配置生效
}
- 给服务提供者server-provider新增配置文件
在resources目录下新增配置文件bootstrap.yml,并配置如下内容
spring:
application:
name: server-provider
cloud:
nacos:
config:
server-addr: localhost:8848 # 注册中心地址
file-extension: yaml # 开启配置动态刷新(可选,默认值:properties)
namespace: public # 命名空间(可选)
group: DEFAULT_GROUP # 分组(可选,默认值:DEFAULT_GROUP)
refresh-enabled: true # 开启配置动态刷新(可选,默认值:true)
discovery:
server-addr: localhost:8848 # 注册中心地址
- 在nacos上新增配置文件:server-provider.yml(该名称必须与服务名 server-provider 一致)
- 创建主启动类 ProviderBootSrap.java
package com.chaoup.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现
public class ProviderBootSrap {
public static void main(String[] args) {
SpringApplication.run(ProviderBootSrap.class, args);
}
}
- 启动服务提供者server-provider
查看nacos控制台,服务列表中发现服务提供者server-provider已经注册成功
- 编写个接口,供消费者消费
package com.chaoup.provider.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hellos")
public class Hello {
@GetMapping("/say")
String hello(@RequestParam("name") String name) {
return String.format("hello %s,我是服务提供者", name);
}
}
- 重置服务提供者server-provider,GET请求:http://localhost:8081/hellos/say?name=dj,访问成功!
服务消费者
- 使用idea创建一个服务消费者server-consumer
- 完善服务消费者server-consumer的build.gradle配置
apply plugin:"org.springframework.boot" // 应用spring boot 插件
dependencies {
implementation "org.springframework.boot:spring-boot-starter-web" // spring boot web 核心依赖
implementation "com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery" // nacos服务发现
implementation "com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config" // nacos配置中心
implementation "org.springframework.cloud:spring-cloud-starter-bootstrap" // 启用bootstrap上下文,让bootstrap.yml文件中的nacos配置生效
implementation "org.springframework.cloud:spring-cloud-starter-openfeign" // openfeign
implementation "org.springframework.cloud:spring-cloud-starter-loadbalancer" // loadbalancer
}
- 给服务消费者server-consumer新增配置文件
在resources目录下新增配置文件bootstrap.yml,配置如下
spring:
application:
name: server-consumer
cloud:
nacos:
config:
server-addr: localhost:8848 # 注册中心地址
file-extension: yaml # 开启配置动态刷新(可选,默认值:properties)
namespace: public # 命名空间(可选)
group: DEFAULT_GROUP # 分组(可选,默认值:DEFAULT_GROUP)
refresh-enabled: true # 开启配置动态刷新(可选,默认值:true)
discovery:
server-addr: localhost:8848 # 注册中心地址
- 在nacos上新增配置文件:server-consumer.yml(该名称必须与服务名 server-consumer 一致)
- 创建主启动类 ConsumerBootStrap.java
package com.chaoup.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现
public class ConsumerBootStrap {
public static void main(String[] args) {
SpringApplication.run(ConsumerBootStrap.class, args);
}
}
- 启动服务消费者server-consumer
查看nacos控制台,在服务列表中发现服务消费者server-consumer已经注册成功
- 编写个接口,测试下
package com.chaoup.consumer.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/tests")
public class Test {
@GetMapping("/test1")
public String test1(@RequestParam("name") String name) {
return String.format("%s,测试成功!", name);
}
}
- 重置服务B,然后GET请求:http://localhost:8082/tests/test1?name=dj,访问成功!
使用openFeign
- 在消费者server-consumer中创建feign客户端
package com.chaoup.consumer.feign.clients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "server-provider")
public interface HelloClient {
@GetMapping("/hellos/say")
String hello(@RequestParam("name") String name);
}
- 修改消费者server-consumer的controller
package com.chaoup.consumer.controller;
import com.chaoup.consumer.feign.clients.HelloClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/tests")
public class Test {
@Resource
private HelloClient helloClient;
@GetMapping("/test1")
public String test1(@RequestParam("name") String name) {
return helloClient.hello(name);
// return String.format("%s,测试成功!", name);
}
}
- 服务消费者的主启动类上加上 @EnableFeignClients 注解
package com.chaoup.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现
@EnableFeignClients // 开启feign客户端的自动配置和扫描机制
public class ConsumerBootStrap {
public static void main(String[] args) {
SpringApplication.run(ConsumerBootStrap.class, args);
}
}
- 重启服务消费者server-consumer
也成功注册到nacos
- 再次GET请求:http://localhost:8082/tests/test1?name=dj,访问成功!
至此,一个简易的微服务就搭建完成!