1、微服务概述
1.1 概念
1.2 架构演进
- 单体架构:
将业务的所有功能集中在一个项目中年开发, 打成一个jar包
优点:架构简单,部署成本低
缺点:耦合度高
- 分布式架构
按业务功能对系统进行拆分,每一个业务模块作为独立项目开发,成为一个服务
优点:降低服务耦合,有利于服务升级拓展
缺点:
- 微服务架构
一种经过良好架构设计的分布式架构方案
1.3 微服务技术对比
2. springcloud
2.1 注册中心
2.1.1 eureka集群搭建
- 依赖
description '微服务'
// 第三方插件对应的仓库和类路径
buildscript {
ext {
springBootVersion = '3.0.1'
springCloudVersion = '2022.0.0'
springCloudAlibabaVersion = '2021.0.4.0'
}
repositories {
mavenLocal()
maven { url 'https://maven.aliyun.com/nexus/content/groups/public' }
google()
mavenCentral()
}
// 此处先引入springboot插件
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
}
}
allprojects {
group 'com.xing'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'java-library' // 提供api依赖方式支持
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
tasks.withType(JavaCompile).tap {
configureEach {
options.encoding = 'UTF-8'
}
}
// 设置仓库地址
repositories {
mavenLocal()
// aliyun镜像
maven { url 'https://maven.aliyun.com/repository/public' }
maven {url 'https://repo.spring.io/milestone'}
mavenCentral()
}
test {
useJUnitPlatform()
}
}
subprojects {
// 使用springboot支持插件
apply plugin:'org.springframework.boot'
// 提供dependencyManagement支持
apply plugin: "io.spring.dependency-management"
// 相当于maven的dependencyManagement标签
dependencyManagement{
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "com.alibaba.cloud:spring-cloud-alibaba-dependencies:${springCloudAlibabaVersion}"
}
}
dependencies {
// 提供注解处理器
annotationProcessor 'org.projectlombok:lombok:1.18.24'
implementation 'org.projectlombok:lombok:1.18.24'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.24'
testImplementation 'org.projectlombok:lombok:1.18.24'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0'
}
}
project(':microservice-register'){
description '注册中心'
dependencies {
api 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'
}
}
project(':microservice-register:eureka-server1'){
dependencies {
implementation project(':microservice-register')
}
}
project(':microservice-register:eureka-server2'){
dependencies {
implementation project(':microservice-register')
}
}
project(':microservice-service:microservice-order'){
description '订单服务'
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'mysql:mysql-connector-java:8.0.31'
implementation 'com.alibaba:druid-spring-boot-starter:1.2.14'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.0'
}
}
project(':microservice-service:microservice-user'){
description '用户服务'
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'mysql:mysql-connector-java:8.0.31'
implementation 'com.alibaba:druid-spring-boot-starter:1.2.14'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.0'
}
}
- 修改hosts文件
127.0.0.1 eureka1
127.0.0.1 eureka2
- 配置1
server:
port: 9001
spring:
application:
name: eureka-server1
eureka:
instance:
hostname: eureka1 #eureka服务端的实例名称
instance-id: eureka-server1
client:
register-with-eureka: true #false表示不向注册中心注册自己
fetch-registry: true #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
service-url:
defaultZone: http://eureka2:9002/eureka
- 配置2
server:
port: 9002
spring:
application:
name: eureka-server2
eureka:
instance:
hostname: eureka2 #eureka服务端的实例名称
instance-id: eureka-server2
client:
register-with-eureka: true #false表示不向注册中心注册自己
fetch-registry: true #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
service-url:
defaultZone: http://eureka1:9001/eureka
- 服务端代码
@SpringBootApplication
@EnableEurekaServer
public class EurekaFirstApp {
public static void main(String[] args) {
SpringApplication.run(EurekaFirstApp.class,args);
}
}
@SpringBootApplication
@EnableEurekaServer
public class EurekaSecondApp {
public static void main(String[] args) {
SpringApplication.run(EurekaSecondApp.class,args);
}
}
- 客户端配置1
server:
port: 8001
spring:
application:
name: microservice-order
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1
username: root
password: root
mybatis:
type-aliases-package: com.xing.model.pojo
mapper-locations: classpath:/mapper/*Mapper.xml
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:9001/eureka
- 客户端配置2
port: 8002
spring:
application:
name: microservice-user
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1
username: root
password: root
mybatis:
type-aliases-package: com.xing.model.pojo
mapper-locations: classpath:/mapper/*Mapper.xml
configuration:
map-underscore-to-camel-case: true
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:9002/eureka
- 客户端代码
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan(value = "com.xing.mapper")
public class OrderApp {
public static void main(String[] args) {
SpringApplication.run(OrderApp.class,args);
}
}
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan(value = "com.xing.mapper")
public class UserApp {
public static void main(String[] args) {
SpringApplication.run(UserApp.class,args);
}
}
2.1.2 nacos项目搭建
- 导入依赖
description 'springcloud-01'
buildscript {
ext {
springBootVersion = '2.7.4'
springCloudVersion = '2021.0.3'
springCloudAlibabaVersion = '2021.0.1.0'
}
// 配制插件仓库
repositories {
mavenLocal()
maven { url 'https://maven.aliyun.com/nexus/content/groups/public' }
google()
mavenCentral()
}
// 此处先引入springboot插件
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
}
}
allprojects {
group 'com.xingyu'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'java-library' // 提供api依赖方式支持
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
// 设置仓库地址
repositories {
mavenLocal()
// aliyun镜像
maven { url 'https://maven.aliyun.com/repository/public' }
maven {url 'https://repo.spring.io/milestone'}
mavenCentral()
}
// 设置公用的依赖
dependencies {
// 提供注解处理器
annotationProcessor 'org.projectlombok:lombok:1.18.24'
implementation 'org.projectlombok:lombok:1.18.24'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.24'
testImplementation 'org.projectlombok:lombok:1.18.24'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0'
// junit5的支持,4不需要
test {
useJUnitPlatform()
}
}
}
// 配置所有子工程
subprojects {
// 提供dependencyManagement支持
apply plugin: "io.spring.dependency-management"
// 相当于maven的dependencyManagement标签
dependencyManagement{
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "com.alibaba.cloud:spring-cloud-alibaba-dependencies:${springCloudAlibabaVersion}"
}
}
}
project(":microservice-gateway"){
description '网关服务'
apply plugin:'org.springframework.boot'
dependencies {
dependencies {
api ('org.springframework.cloud:spring-cloud-starter-gateway') {
exclude(module:'org.springframework.boot:spring-boot-starter-web')
}
api 'org.springframework.cloud:spring-cloud-starter-bootstrap'
api 'org.springframework.cloud:spring-cloud-starter-loadbalancer'
api 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery'
api 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config'
}
}
}
project(":microservice-service"){
description '封装所有的微服务'
subprojects {
// 使用springboot支持插件
apply plugin:'org.springframework.boot'
dependencies {
api 'org.springframework.boot:spring-boot-starter-web'
api 'org.springframework.cloud:spring-cloud-starter-bootstrap'
api 'org.springframework.cloud:spring-cloud-starter-openfeign'
api 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery'
api 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config'
}
}
}
- 配置
server:
port: 8001
servlet:
context-path: /microservice-admin
spring:
application:
name: microservice-admin
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
config:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
- 代码
@SpringBootApplication
@EnableDiscoveryClient
public class AdminApp {
public static void main(String[] args) {
SpringApplication.run(AdminApp.class, args);
}
}
2.2 远程调用-feign
2.2.1 导入依赖
api 'org.springframework.cloud:spring-cloud-starter-openfeign'
2.2.2 代码
- 开启feign支持
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class AdminApp {
public static void main(String[] args) {
SpringApplication.run(AdminApp.class, args);
}
}
- feign接口编写
@FeignClient(value = "microservice-login")
public interface FeignInterface {
@GetMapping("/microservice-login/loginController/login")
String login(@RequestParam("userName") String userName);
}
- 服务提供
@RestController
@RequestMapping("loginController")
public class LoginController {
@GetMapping("login")
public String login(@RequestParam("userName") String userName){
System.out.println(userName);
return "success";
}
}
2.3 负载均衡
2.3.1 导入依赖
api 'org.springframework.cloud:spring-cloud-starter-bootstrap' // 提供bootstrap的支持
api 'org.springframework.cloud:spring-cloud-starter-loadbalancer'
2.3.1 代码
@Configuration
// 配置client
@LoadBalancerClients(@LoadBalancerClient(name = "microservice-login",configuration = MyConfig.class))
public class MyConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public ReactorLoadBalancer<ServiceInstance> reactorLoadBalancer(Environment environment, LoadBalancerClientFactory factory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RoundRobinLoadBalancer(factory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
}
2.4 网关gateway
2.4.1 导入依赖
project(":microservice-gateway"){
description '网关服务'
apply plugin:'org.springframework.boot'
dependencies {
dependencies {
api ('org.springframework.cloud:spring-cloud-starter-gateway') {
exclude(module:'org.springframework.boot:spring-boot-starter-web')
}
api 'org.springframework.cloud:spring-cloud-starter-bootstrap' // 提供bootstrap的支持
api 'org.springframework.cloud:spring-cloud-starter-loadbalancer'
api 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery'
api 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config'
}
}
}
2.3.1 代码
server:
port: 8000
spring:
application:
name: microservice-gateway
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
config:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
gateway:
routes:
- id: microservice-login
uri: lb://microservice-login
predicates:
- Path=/microservice-login/loginController/**
- id: microservice-admin
uri: lb://microservice-admin
predicates:
- Path=/microservice-admin/AdminController/**
@SpringBootApplication
@EnableDiscoveryClient
public class GateWayApp {
public static void main(String[] args) {
SpringApplication.run(GateWayApp.class, args);
}
}
@Component
public class MyGlobalFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("MyGlobalFilter running");
return chain.filter(exchange);
}
}