SpringCloud概述---Rest学习搭建---Eureka集群
SpringCloud
-
分布式
-
生态
-
SpringBoot
1. 概述
微服务架构4个核心问题
- 服务很多,客户端怎么访问
- 这么多服务,服务之间如何通信
- 这么多服务,如何治理
- 服务挂了怎么办
解决方案
1、Spring Cloud NetFlix(一站式解决方案)
- API网关,zuul组件
- Feign — HttpClient — Http通信方式,同步,阻塞
- 服务注册发现 Eureka
- 熔断机制 Hystrix
2、Apache Dubbo Zookeeper(半自动,需要整合别人的)
- API 没有,需要找第三方组件,或者自己实现
- Dubbo 高性能基于RPC通信框架
- Zookeeper 服务注册与发现
- 没有熔断机制 借助Hystrix
Dubbo这个方案并不完善
3、Spring Cloud Alibaba(一站式解决方案)更简单
- API
- HTTP,RPC
- 注册与发现
- 熔断机制
- 路由网关
2. 微服务概述
2.1 什么是微服务
微服务(Microservice Architecture)是近几年年流行的一种架构思想,关于它的概念很难一言以蔽之
原文:https://martinfowler.com/articles/microservices.html
-
就目前而言,对于微服务,业界没有一个统一的、标准的定义
-
但通常而言,微服务架构是一种架构模式,或者说是一种架构风格,它提倡将单一的应用程序划分成一组小的服务,每个服务运行在其独立的自己的进程内,服务之间互相协调,相互配置,为用户提供最终价值。服务之间采用轻量级的通信机制互相沟通,每个服务都围绕着具体的业务进行构建,并且能够被独立的部署到生产环境中,另外,应尽量避免统一的、集中式的服务管理机制,对具体的一个服务而言,应根据业务上下文,选择合适的语言、工具对其进行构建,可以有一个非常轻量级的集中式管理来协调这些服务,可以使用不同的语言来编写,也可以使用不同的数据存储
-
微服务化的核心就是将传统的一站式应用,根据业务拆分成一个一个的服务,彻底地去耦合,每一个微服务提供单个业务功能的服务,一个服务做一件事,从技术角度看就是一种小而独立的处理过程,类似进程的概念,能够自行单独启动或销毁,拥有自己独立的数据库
2.2 微服务与微服务架构
微服务
强调的是服务的大小,他关注的是某一个点,是具体解决某一个问题 / 提供落地对应服务的一个服务应用,狭义的看,可以看作IDEA中一个个微服务工程,或者Moudel
IDEA工具里面使用Maven开发的一个个独立的小的Moudel,他具体是使用SpringBoot开发的一个小模块,专业的事情交给专业的模块来完成,一个模块就坐着一件事情
强调的是一个个的个体,每个个体完成一个具体的任务或者功能
微服务框架
一种新的框架形式,Martin Fowler,2014年提出
微服务架构是一种架构模式,它提倡将单一应用程序划分成一组小的服务,服务之间互相协调,互相配合,为用户提供最终价值。每个服务运行在其独立的进程中,服务于服务间采用轻量级的通信机制互相协作,每个服务都围绕着具体的业务进行构建,并且能够被独立的部署到生产环境中,另外,应尽量避免统一的、集中式的服务管理机制,对具体的一个服务而言,应根据业务上下文,选择合适的语言、工具对其进行构建
2.3 微服务优缺点
优点
- 每个服务足够内聚,足够小,代码容易理解,这样能聚焦一个指定的业务功能或业务需求
- 开发简单,开发效率提高,一个服务可能就是专一的只干一件事
- 微服务能够被小团队单独开发,这个小团队是2~5人的开发人员组成
- 微服务是松耦合的,是有功能意义的服务,无论是在开发阶段或部署阶段都是独立的
- 微服务能使用不同的语言开发
- 易于和第三方集成,微服务允许容易且灵活的方式继承自动部署,通过持续集成工具,如jenkins,Hudson,bamboo
- 微服务易于被一个开发人员理解、修改和维护,这样小团队能够更关注自己的工作成果。无需通过合作才能体现价值
- 微服务允许你利用融合最新技术
- 微服务只是业务逻辑的代码,不会和 HTML、 CSS 或其它界面混合
- 每个微服务都有自己的存储能力,可以有自己的数据库,也可以有统一数据库
缺点
- 开发人员要处理分布式系统的复杂性
- 多服务运维难度,随着服务的增加,韵运维的压力也在增加
- 系统部署依赖
- 服务间通信成本
- 数据一致性
- 系统集成测试
- 性能监控
2.4 微服务技术栈有哪些
微服务条目 | 落地技术 |
---|---|
服务开发 | SpringBoot、Spring、SpringMVC |
服务配置与管理 | Netflix公司的Archaius、阿里的Diamond等 |
服务注册与发现 | Eureka、Consul、Zookeeper等 |
服务调用 | Rest、PRC,gRPC |
服务熔断器 | Hystrix、Envoy等 |
负载均衡 | Ribbon、Nginx等 |
服务接口调用(客户端调用服务的简化工具) | Feign等 |
消息队列 | Kafka、RabbitMQ、ActiveMQ等 |
服务配置中心管理 | SpringCloudConfig、Chef等 |
服务路由(API网关) | Zuul等 |
服务监控 | Zabbix、Nagios、Metrics、Specatator等 |
全链路追踪 | Zipkin、Brave、Dapper等 |
服务部署 | Docker、OpenStack、Kubernetes等 |
数据流操作开发包 | SpringCloud Stream(封装Redis、Rabbit、Kafka等发送接收消息) |
事件消息总线 | SpringCould Bus |
2.5 为什么选择SpringCloud作为微服务架构
1、选型依据
- 整体解决方案和框架成熟度
- 社区热度
- 可维护性
- 学习曲线
2、当前各大IT公司用的微服务架构有哪些
- 阿里 dubbo + HFS
- 京东 JSF
- 新浪 Motan
- 当当网 DubboX
3、各微服务框架对比
功能点/服务框架 | Netflix/SpringCloud | Motan | gRPC | Thrift | Dubbo/DubboX |
---|---|---|---|---|---|
功能定位 | 完整的微服务框架 | RPC框架,但整合了ZK或Consul,实现集群环境的基本服务注册/发现 | PRC框架 | PRC框架 | 服务框架 |
支持Rest | 是,Ribbon支持多种可插拔的序列化选择 | 否 | 否 | 否 | 否 |
支持RPC | 否 | 是(Hession2) | 是 | 是 | 是 |
支持多语言 | 是 | 否 | 是 | 是 | 否 |
负载均衡 | 是(服务端zuul+客户端Ribbon),zuul-服务,动态路由,云端负载均衡 Eureka(针对中间层服务器) | 是(客户端) | 否 | 否 | 是(客户端) |
配置服务 | Netflix Archaius,Spring Cloud Config Server集中配置 | 是(zookeeper提供) | 否 | 否 | 否 |
服务调用链监控 | 是(zuul),zuul提供边缘服务,API网关 | 否 | 否 | 否 | 否 |
高可用/容错 | 是(服务端Hystrix + 客户端Ribbon) | 是(客户端) | 否 | 否 | 是(客户端) |
典型应用案例 | Netflix | Sina | |||
社区活跃度 | 高 | 一般 | 高 | 一般 | 2017年后重新开始维护,之前中断了5年 |
学习难度 | 中 | 低 | 高 | 高 | 低 |
文档丰富程度 | 高 | 一般 | 一般 | 一般 | 高 |
其它 | Spring Cloud Bus为我们的应用程序带来了更多管理端点 | 支持降级 | Netflix内部在开发集成gRPC | IDL定义 | 实践的公司比较多 |
3. Spring Cloud入门概述
3.1 什么是Spring Cloud
Spring 官网:https://spring.io/
- SpringCloud, 基于SpringBoot提供了一套微服务解决方案,包括服务注册与发现,配置中心,全链路监
控,服务网关,负载均衡,熔断器等组件,除了基于NetFlix的开源组件做高度抽象封装之外,还有一些选型中立的开源组件。 - SpringCloud利用SpringBoot的开发便利性,巧妙地简化了分布式系统基础设施的开发,SpringCloud为开发人员提供了快速构建分布式系统的一些工具,包括配置管理,服务发现,断路器,路由,微代理,事件总线,全局锁,决策竞选,分布式会话等等,他们都可以用SpringBoot的开发风格做到一键启动和部署。
- SpringBoot并没有重复造轮子,它只是将目前各家公司开发的比较成熟,经得起实际考验的服务框架组合起来,通过SpringBoot风格进行再封装,屏蔽掉了复杂的配置和实现原理,最终给开发者留出了一套简单易懂,易部署和易维护的分布式系统开发工具包
- SpringCloud 是 分布式微服务架构下的一站式解决方案,是各个微服务架构落地技术的集合体,俗称微服务全桶。
3.2 SpringCloud 和 SpringBoot关系
SpringBoot专注于快速方便的开发单个个体微服务。
SpringCloud是关注全局的微服务协调整理治理框架,它将SpringBoot开发的一个个单体微服务整合并管理起来,为各个微服务之间提供:配置管理,服务发现,断路器,路由,微代理,事件总线,全局锁,决策竞选,分布式会话等等集成服务。
SpringBoot可以离开SpringCloud独立使用,开发项目,但是SpringCloud离不开SpringBoot,属于依赖关系
SpringBoot专注于快速、方便的开发单个个体微服务,SpringCloud关注全局的服务治理框架
3.3 Dubbo 和 SpringCloud技术选型
1、分布式 + 服务治理 Dubbo
目前成熟的互联网架构:应用服务化拆分 + 消息中间件
Dubbo | SpringCloud | |
---|---|---|
服务注册中心 | Zookeeper | Spring Cloud Netfilx Eureka |
服务调用方式 | RPC | REST API |
服务监控 | Dubbo-monitor | Spring Boot Admin |
断路器 | 不完善 | Spring Cloud Netfilx Hystrix |
服务网关 | 无 | Spring Cloud Netfilx Zuul |
分布式配置 | 无 | Spring Cloud Config |
服务跟踪 | 无 | Spring Cloud Sleuth |
消息总栈 | 无 | Spring Cloud Bus |
数据流 | 无 | Spring Cloud Stream |
批量任务 | 无 | Spring Cloud Task |
最大区别:SpringCloud抛弃了Dubbo的RPC通信,采用的是基于HTTP的REST方式
严格来说,这两种方式各有优劣。虽然从一定程度上来说,后者牺牲了服务调用的性能,但也避免了上面提到的原生RPC带来的问题。而且REST相比RPC更为灵活,服务提供方和调用方的依赖只依靠一纸契约,不存在代码级别的强依赖,这在强调快速演化的微服务环境下,显得更加合适
品牌机与组装机的区别
很明显,Spring Cloud的功能比DUBBO更加强大,涵盖面更广,而且作为Spring的拳头项目,它也能够与Spring Framework、Spring Boot、Spring Data、Spring Batch等其他Spring项目完美融合,这些对于微服务而言是至关重要的。使用Dubbo构建的微服务架构就像组装电脑,各环节我们的选择自由度很高,但是最终结果很有可能因为一条内存质量不行就点不亮了,总是让人不怎么放心,但是如果你是一名高手,那这些都不是问题;而Spring Cloud就像品牌机,在Spring Source的整合下,做了大量的兼容性测试,保证了机器拥有更高的稳定性,但是如果要在使用非原装组件外的东西,就需要对其基础有足够的了解
社区支持与更新力度
最为重要的是,DUBBO停止了5年左右的更新,虽然2017.7重启了。对于技术发展的新需求,需要由开发者自行拓展升级(比如当当网弄出了DubboX),这对于很多想要采用微服务架构的中小软件组织,显然是不太合适的,中小公司没有这么强大的技术能力去修改Dubbo源码+周边的一整套解决方案,并不是每一个公司都有阿里的大牛+真实的线上生产环境测试过
解决问题域不一样:Dubbo的定位是一款RPC框架,Spring Cloud的目标是微服务架构下的一站式解决方案
SpringCloud没有采用数字编号的方式命名版本号,而是采用了伦敦地铁站的名称,同时根据字母表的顺序来对应版本时间顺序,比如最早的Realse版本:Angel,第二个Realse版本:Brixton,然后是Camden、Dalston\Edgware,目前最新的是Hoxton SR4 CURRENT GA通用稳定版。
自学参考书:
- SpringCloud Netflix 中文文档:
https://springcloud.cc/spring-cloud-netflix.html - SpringCloud 中文API文档(官方文档翻译版):https://springcloud.cc/spring-cloud-dalston.html
- SpringCloud中文网:
https://springcloud.cc
版本选择
SpringCloud版本 | SpringBoot版本 |
---|---|
2021.0.1-SNAPSHOT | Spring Boot >=2.6.4-SNAPSHOT and <2.7.0-M1 |
2021.0.0 | Spring Boot >=2.6.1 and <2.6.4-SNAPSHOT |
2021.0.0-RC1 | Spring Boot >=2.6.0-RC1 and <2.6.1 |
2021.0.0-M1 | Spring Boot >=2.6.0-M1 and <2.6.0-M3 |
2020.0.5 | Spring Boot >=2.4.0.M1 and <2.6.0-M1 |
Hoxton.SR12 | Spring Boot >=2.2.0.RELEASE and <2.4.0.M1 |
Hoxton.BUILD-SNAPSHOT | Spring Boot >=2.2.0.BUILD-SNAPSHOT |
Hoxton.M2 | Spring Boot >=2.2.0.M4 and <=2.2.0.M5 |
Greenwich.BUILD-SNAPSHO | Spring Boot >=2.1.9.BUILD-SNAPSHOT and <2.2.0.M4 |
Greenwich.SR2 | Spring Boot >=2.1.0.RELEASE and <2.1.9.BUILD-SNAPSHOT |
Greenwich.M1 | Spring Boot >=2.1.0.M3 and <2.1.0.RELEASE |
Finchley.BUILD-SNAPSHOT | Spring Boot >=2.0.999.BUILD-SNAPSHOT and <2.1.0.M3 |
Finchley.SR4 | Spring Boot >=2.0.3.RELEASE and <2.0.999.BUILD-SNAPSHOT |
Finchley.RC2 | Spring Boot >=2.0.2.RELEASE and <2.0.3.RELEASE |
Finchley.RC1 | Spring Boot >=2.0.1.RELEASE and <2.0.2.RELEASE |
Finchley.M9 | Spring Boot >=2.0.0.RELEASE and <=2.0.0.RELEASE |
Finchley.M7 | Spring Boot >=2.0.0.RC2 and <=2.0.0.RC2 |
Finchley.M6 | Spring Boot >=2.0.0.RC1 and <=2.0.0.RC1 |
Finchley.M5 | Spring Boot >=2.0.0.M7 and <=2.0.0.M7 |
Finchley.M4 | Spring Boot >=2.0.0.M6 and <=2.0.0.M6 |
Finchley.M3 | Spring Boot >=2.0.0.M5 and <=2.0.0.M5 |
Finchley.M2 | Spring Boot >=2.0.0.M3 and <2.0.0.M5 |
Edgware.SR5 | 1.5.20.RELEASE |
Edgware.SR5 | 1.5.16.RELEASE |
Edgware.RELEASE | 1.5.9.RELEASE |
Dalston.RC1 | 1.5.2.RELEASE |
Release Train | Boot Version |
---|---|
2021.0.x aka Jubilee | 2.6.x |
2020.0.x aka Ilford | 2.4.x, 2.5.x (Starting with 2020.0.3) |
Hoxton | 2.2.x, 2.3.x (Starting with SR5) |
Greenwich | 2.1.x |
Finchley | 2.0.x |
Edgware | 1.5.x |
Dalston | 1.5.x |
4. Rest学习搭建环境
使用maven创建工程
(一)父工程
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vinjcent</groupId>
<artifactId>springcloud</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>springcloud-api</module>
<module>springcloud-provider-dept-8001</module>
<module>springcloud-consumer-dept-80</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<junit.version>4.13.2</junit.version>
<lombok.version>1.18.22</lombok.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<!-- 打包方式 pom -->
<packaging>pom</packaging>
<!-- 总的依赖管理 -->
<dependencyManagement>
<dependencies>
<!--SpringCloud的依赖-->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--SpringBoot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.6.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!--SpringBoot启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- 日志和测试 -->
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--logback-core-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.11</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
(二)子模块-接口(springcloud-api)
package com.vinjcent.springcloud.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@NoArgsConstructor
@Accessors(chain = true) // 链式写法
public class Department implements Serializable { // 实体类 orm 类表关系映射
private Long deptId; // 主键
private String deptName; // 部门名
// 这个数据存在哪个数据库的字段 微服务,一个服务对应一个数据库,同一个信息可能存在不同的数据库
private String db_source;
public Department(String deptName) {
this.deptName = deptName;
}
/**
* 链式写法:
* Department dept = new Department();
*
* 原来dept.setName();
*
* 加了之后:
* dept
* .setDeptName()
* .setDeptId()
* .setDb_source();
*
*/
}
(三)子模块-提供者(springcloud-provider-dept-8001)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.vinjcent</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-provider-dept-8001</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- 我们需要拿到实体类,所以要配置api module -->
<dependency>
<groupId>com.vinjcent</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--jetty-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<!--热部署工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
# 端口号
server:
port: 8001
# mybatis配置
mybatis:
type-aliases-package: com.vinjcent.springcloud.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
config-location: classpath:mybatis/mybatis-config.xml
# cache-enabled: true
# spring配置
spring:
application:
name: springcloud-provider-dept
datasource: # 数据源
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
dbcp2:
min-idle: 5
initial-size: 5
max-idle: 20
max-wait-millis: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
package com.vinjcent.springcloud.mapper;
import com.vinjcent.springcloud.pojo.Department;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface DepartmentMapper {
int addDept(Department department);
Department queryById(Long id);
List<Department> queryAllDepartments();
}
package com.vinjcent.springcloud.service;
import com.vinjcent.springcloud.pojo.Department;
import java.util.List;
public interface DepartmentService {
int addDept(Department department);
Department queryById(Long id);
List<Department> queryAllDepartments();
}
package com.vinjcent.springcloud.service.imp;
import com.vinjcent.springcloud.mapper.DepartmentMapper;
import com.vinjcent.springcloud.pojo.Department;
import com.vinjcent.springcloud.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DepartmentServiceImpl implements DepartmentService {
private DepartmentMapper departmentMapper;
@Autowired
public void setDepartmentMapper(DepartmentMapper departmentMapper) {
this.departmentMapper = departmentMapper;
}
@Override
public int addDept(Department department) {
return departmentMapper.addDept(department);
}
@Override
public Department queryById(Long id) {
return departmentMapper.queryById(id);
}
@Override
public List<Department> queryAllDepartments() {
return departmentMapper.queryAllDepartments();
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vinjcent.springcloud.mapper.DepartmentMapper">
<insert id="addDept" parameterType="Department">
insert into department(deptName,db_source)
values (#{deptName},DATABASE())
</insert>
<select id="queryById" resultType="Department" parameterType="Long">
select * from department where deptId = #{id}
</select>
<select id="queryAllDepartments" resultType="Department">
select * from department
</select>
</mapper>
package com.vinjcent.springcloud.controller;
import com.vinjcent.springcloud.pojo.Department;
import com.vinjcent.springcloud.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
// 提供Restful服务
@RestController
public class DepartmentController {
private DepartmentService departmentService;
@Autowired
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
@PostMapping("/dept/add")
public int addDept(Department department){
return departmentService.addDept(department);
}
@GetMapping("/dept/get/{id}")
public Department addDept(@PathVariable("id") Long id){
return departmentService.queryById(id);
}
@GetMapping("/dept/list")
public List<Department> addDept(){
return departmentService.queryAllDepartments();
}
}
// 启动类
@SpringBootApplication
public class DeptProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_8001.class,args);
}
}
(四)子模块-消费者(springcloud-consumer-dept-80)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.vinjcent</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-consumer-dept-80</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--实体类 + web-->
<dependencies>
<dependency>
<groupId>com.vinjcent</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--热部署工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
server:
port: 80
package com.vinjcent.springcloud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ConfigBean { // @Configuration --> 相当于 spring 的 application.xml
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
package com.vinjcent.springcloud.controller;
import com.vinjcent.springcloud.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@SuppressWarnings("all")
public class DeptConsumerController {
// 理解: 消费者,不应该有service层
// 支持RestFul RestTemplate 供我们直接调用
// (url,实体:map,Class<T> responseType)
@Autowired
private RestTemplate restTemplate; // 提供多种便捷访问远程http服务的方法,简单的Restful服务模板
//http://localhost:8001/dept/list
private static final String REST_URL_PREFIX = "http://localhost:8001";
@RequestMapping("/consumer/dept/list")
public List<Department> getAll(){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class);
}
@RequestMapping("/consumer/dept/add")
public int add(Department department){
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",department,int.class);
}
@RequestMapping("/consumer/dept/get/{id}")
public Department getDept(@PathVariable("id")Long id){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Department.class);
}
}
package com.vinjcent.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer_80.class,args);
}
}
与Zookeeper和Dubbo相比,不用在消费者中写与提供者一一对应的service(省去了@Reference注解)
5. Eureka服务注册与发现
5.1 什么是Eureka
Eureka:怎么读? [juˈriːkə]
Netflix 在设计Eureka 时,遵循的就是AP原则
CAP原则又称CAP定理,指的是在一个分布式系统中
- 一致性(Consistency)
- 可用性(Availability)
- 分区容错性(Partition tolerance)
CAP 原则指的是,这三个要素最多只能同时实现两点,不可能三者兼顾
Eureka是Netflix的一个子模块,也是核心模块之一。Eureka是一个基于REST的服务,用于定位服务,以实现云端中间层服务发现和故障转移,服务注册与发现对于微服务来说是非常重要的,有了服务发现与注册,只需要使用服务的标识符,就可以访问到服务,而不需要修改服务调用的配置文件了,功能类似于Dubbo的注册中心,比如Zookeeper
5.2 原理及讲解
Eureka的基本架构:
- SpringCloud 封装了NetFlix公司开发的Eureka模块来实现服务注册和发现
- Eureka采用了C-S的架构设计,EurekaServer 作为服务注册功能的服务器,它是服务注册中心
- 而系统中的其他微服务。使用Eureka的客户端连接到EurekaServer并维持心跳连接。这样系统的维护人员就可以通过EurekaServer来监控系统中各个微服务是否正常运行,SpringCloud的一些其他模块(比如Zuul)就可以通过EurekaServer来发现系统中的其他微服务,并执行相关的逻辑
Dubbo架构对比
Eureka 包含两个组件:Eureka Server 和 Eureka Client
Eureka Server 提供服务注册服务,各个节点启动后,会在EurekaServer中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到
Eureka Client是一个Java客户端,用于简化EurekaServer的交互,客户端同时也具备一个内置的,使用轮询负载算法的负载均衡器。在应用启动后,将会向EurekaServer发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将会从服务注册表中把这个服务节点移除掉(默认周期为90秒)
三大角色
- Eureka Server:提供服务的注册于发现 Zookeeper
- Service Provider:将自身服务注册到Eureka中,从而使消费方能够找到
- Service Consumer:服务消费方从Eureka中获取注册服务列表,从而找到消费服务
5.3 服务构建
1.erueka-server服务端
- 建立springcloud-eureka-7001模块
- 编辑pom.xml
<!--导包-->
<dependencies>
<!--Eureka服务端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
<!--热部署工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
- application.yaml
server:
port: 7001
# Eureka配置
eureka:
instance:
hostname: localhost # Eureka服务端的实例名称
client:
register-with-eureka: false # 表示是否向Eureka注册中心注册自己
fetch-registry: false # 如果为false,表示自己为注册中心
service-url: # 表示与eureka交互的地址(监控页面)
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
- 启动类加上注解
package com.vinjcent.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer // EnableEurekaServer 服务端启动类,可以接受别人注册进来
public class EurekaServer_7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaServer_7001.class,args);
}
}
先启动7001服务端后启动8001客户端进行测试,然后访问监控页http://localhost:7001/ 产看结果如图,成功
修改eureka上的默认描述信息
# Eureka的配置,服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
instance:
instance-id: springcloud-provider-dept8001 # 修改eureka上的默认描述信息
actuator与注册微服务信息完善
配置关于服务加载的监控信息
在springcloud-provider-dept-8001导入jar包
<!--actuator完善监控信息-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
修改springcloud-provider-dept-8001模块中application.yml
# info配置
info:
username: vinjcent
company.name: blog.vinjcent.com
# springboot 2.3.x 引入actuator需要声明导出的接口,否则不会像早期版本那样自动映射出去
# 同时需要访问localhost:8001/actuator/env 才能访问到
management:
endpoints:
web:
exposure:
include: "*"
访问localhost也行,因为两个都代表本机
如果此时停掉springcloud-provider-dept-8001 等30s后 监控会开启保护机制:
Eureka的自我保护机制
自我保护机制:好死不如赖活着
一句话总结:某时刻某一个微服务不可以用了,eureka不会立刻清理,依旧会对该微服务的信息进行保存!
- 默认情况下,如果EurekaServer在一定时间内没有接收到某个微服务实例的心跳,EurekaServer将会注销该实例(默认90秒)。但是当网络分区故障发生时,微服务与Eureka之间无法正常通行,以上行为可能变得非常危险了—因为微服务本身其实是健康的,此时本不应该注销这个服务。Eureka通过 自我保护机制 来解决这个问题—当EurekaServer节点在短时间内丢失过多客户端时(可能发生了网络分区故障),那么这个节点就会进入自我保护模式。一旦进入该模式,EurekaServer就会保护服务注册表中的信息,不再删除服务注册表中的数据(也就是不会注销任何微服务)。当网络故障恢复后,该EurekaServer节点会自动退出自我保护模式
- 在自我保护模式中,EurekaServer会保护服务注册表中的信息,不再注销任何服务实例。当它收到的心跳数重新恢复到阈值以上时,该EurekaServer节点就会自动退出自我保护模式。它的设计哲学就是宁可保留错误的服务注册信息,也不盲目注销任何可能健康的服务实例。一句话:好死不如赖活着
- 综上,自我保护模式是一种应对网络异常的安全保护措施。它的架构哲学是宁可同时保留所有微服务(健康的微服务和不健康的微服务都会保留),也不盲目注销任何健康的微服务。使用自我保护模式,可以让Eureka集群更加的健壮和稳定。在SpringCloud中,可以使用
eureka.server.enable-self-preservation = false
禁用自我保护模式 【不推荐关闭自我保护机制】
springcloud-provider-dept-8001服务发现 Discovery(团队开发比较常用)
对于注册进eureka里面的微服务,可以通过服务发现来获得该服务的信息 【对外暴露服务】
修改springcloud-provider-dept-8001工程中的DepartmentController
新增一个方法
@RequestMapping("/dept/discovery")
// 注册进来的微服务,获取一些消息
public Object Discovery(){
// 获取微服务列表的清单
List<String> services = client.getServices();
System.out.println("discovery=>services"+services);
// 得到具体的微服务信息,通过具体的微服务id,applicationName
List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
for (ServiceInstance instance : instances) {
System.out.println(
instance.getHost()+"\t"+
instance.getPort()+"\t"+
instance.getUri()+"\t"+
instance.getServiceId()+"\t"
);
}
return this.client;
}
主启动类增加一个注释
// 启动类
@SpringBootApplication
@EnableEurekaClient // 在服务启动后自动注册到Eureka中
@EnableDiscoveryClient // 服务发现
public class DeptProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_8001.class,args);
}
}
启动Eureka服务,启动8001提供者
访问测试 http://localhost:8001/dept/discovery
5.4. 对比和Zookeeper区别(重要)
1.回顾CAP原则
RDBMS (Mysql、Oracle、sqlServer)===>ACID
NoSQL(redis、mongdb)===> CAP
2.ACID是什么?
- A(Atomicity)原子性
- C(Consistency) 一致性
- I (Isolation)隔离性
- D(Durability)持久性
3.CAP是什么?
- C(Consistency)一致性
- A(Availability)可用性
- P(Partition tolerance)分区容错性
CAP的三进二:CA、AP、CP
CAP理论的核心
一个分布式系统不可能同时很好的满足一致性,可用性和分区容错性这三个需求
根据CAP原理,将NoSQL数据库分成了满足CA原则,满足CP原则和满足AP原则三大类:
- CA:单点集群,满足一致性,可用性的系统,通常可扩展性较差
- CP:满足一致性,分区容错性的系统,通常性能不是特别高
- AP:满足可用性,分区容错性的系统,通常可能对一致性要求低一些
著名的CAP理论指出,一个分布式系统不可能同时满足C(一致性)、A(可用性)、P(容错性)
由于分区容错性P在分布式系统中是必须要保证的,因此我们只能在A和C之间进行权衡。
- Zookeeper保证的是CP
- Eureka保证的是AP
Zookeeper保证的是CP
当向注册中心查询服务列表时,我们可以容忍注册中心返回的是几分钟以前的注册信息,但不能接受服务直接down掉不可用。也就是说,服务注册功能对可用性的要求要高于一致性。但是zk会出现这样一种情况,当master节点因为网络故障与其他节点失去联系时,剩余节点会重新进行leader选举。问题在于,选举leader的时间太长,30~120s,且选举期间整个zk集群都是不可用的,这就导致在选举期间注册服务瘫痪。在云部署的环境下,因为网络问题使得zk集群失去master节点是较大概率会发生的事件,虽然服务最终能够恢复,但是漫长的选举时间导致的注册长期不可用是不能容忍的
Eureka保证的是AP
Eureka看明白了这一点,因此在设计时就优先保证可用性。Eureka各个节点都是平等的,几个节点挂掉不会影响正常节点的工作,剩余的节点依然可以提供注册和查询服务。而Eureka的客户端在向某个Eureka注册时,如果发现连接失败,则会自动切换至其他节点,只要有一台Eureka还在,就能保住注册服务的可用性,只不过查到的信息可能不是最新的,除此之外,Eureka还有一种自我保护机制,如果在15分钟内超过85%的节点都没有正常的心跳,那么Eureka就认为客户端与注册中心出现了网络故障,此时会出现以下几种情况:
- Eureka不再从注册列表中移除因为长时间没收到心跳而应该过期的服务
- Eureka仍然能够接受新服务的注册和查询请求,但是不会被同步到其他节点上(即保证当前节点依然可用)
- 当网络稳定时,当前实例新的注册信息会被同步到其他节点中
因此,Eureka可以很好的应对因网络故障导致部分节点失去联系的情况,而不会像zookeeper那样使整个注册服务瘫痪