微服务的4个核心问题:
解决方案:
1.什么是微服务?
2.微服务之间怎么进行通信的?
3.springcloud和dubbo有什么区别?
4.springboot和springcloud,谈谈对他们的理解?
5.什么是服务熔断?什么是服务降级?
6.微服务的优缺点分别是什么?
7.微服务技术栈?
8.eureka和zookeeper都可以提供服务注册与发现的功能,说说两个的区别?
微服务:强调的是服务的大小,关注的是某一个点,是具体解决某一个问题/提供落地对应服务的一个服务应用
微服务架构:一种新的架构形式,提倡将单一应用程序划分为一组小的服务,服务之间互相协调,互相配合,为用户提供最终价值。
优点:
缺点:
微服务条目 | 落地技术 |
---|---|
服务开发 | SpringBoot,Spring,SpringMVC |
服务配置与管理 | Netfix公司的Archaius,阿里的Diamond等 |
服务注册与发现 | Eureka,Consul,zookeeper |
服务调用 | Rest,RPC,gRPC |
服务熔断器 | Htstrix、Envoy |
负载均衡 | Ribbon Nginx |
服务接口调用(客户端调用服务的简化工具) | Fegin |
消息队列 | Kafka RabbitMQ ActiveMQ |
服务配置中心管理 | SpringCloudConfig Chef |
服务路由(API网关) | Zuul |
服务监控 | Zabbix Nagios Metrics Specatator |
全链路追踪 | Zipkin Brave Dapper |
服务部署 | Docker OpenStack Kubernetes |
数据流操作开发包 | SpringCloud Stream(封装与redis,rabbit kafka等发送接收消息) |
事件消息总线 | SpringCloud Bus |
选型依据
当前IT公司的微服务架构?
各微服务框架对比
功能点/服务框架 | Netfix/SpringCloud | Motan | gRPC | Thrift | Dubbo/DubboX |
---|---|---|---|---|---|
功能定位 | 完整的微服务框架 | RPC框架,但整合了ZK或Consul,实现集群环境的基本服务注册/发现 | RPC框架 | RPC框架 | 服务框架 |
支持Rest | 是,Ribbon | 否 | 否 | 否 | 否 |
支持RPC | 否 | 是(Hession2) | 是 | 是 | 是 |
支持对语言 | 是(Rest形式) | 否 | 是 | 是 | 否 |
负载均衡 | 是(服务端zuul+客户端Ribbon),zuul-服务,动态路由,云端负载均衡Eureka(针对中间层服务层) | 是(客户端) | 否 | 否 | 是(客户端) |
配置服务 | Netfix Archaius,SpringCloud Config Server 集中配置 | 是(zookeeper提高) | 否 | 否 | 否 |
服务调用链监控 | 是(zuul),zuul提高编译服务,API网关 | 否 | 否 | 否 | 否 |
高可用/容错 | 是(服务端Hystrix——客户端Ribbon) | 是(客户端) | 否 | 否 | 是(客户端) |
典型应用案例 | Netfix | Sina | |||
社区活跃程度 | 高 | 一般 | 高 | 一般 | |
其他 | SpringCloudBus为我们的应用程序带来了更多管理断点 | 支持降级 | Netfix内部再开发集成gRPC | IDL定义 | 实践的公司比较多 |
目前成熟的传统互联网架构:应用服务化拆分+消息中间件
社区活跃度:
结果:
Dubbo | SpringCloud | |
---|---|---|
服务注册中心 | zookeeper | Spring Cloud Netfix Eureka |
服务调度方式 | RPC | Rest API |
服务监控 | Dubbo-monitor | Spring Boot Admin |
断路器 | 不完善 | Spring Cloud Netfix Hystrix |
服务网关 | 无 | Spring Cloud Netfix Zuul |
分布式配置 | 无 | Spring Cloud Config |
服务追踪 | 无 | Spring Cloud Seluth |
消息总线 | 无 | Spring Cloud Bus |
数据流 | 无 | Spring Cloud Stream |
批量任务 | 无 | Spring Cloud Task |
最大区别:SpringCloud抛弃了Dubbo的RPC通信,基于HTTP的RESTful方式
spring官网:Spring Cloud
springCloud中文文档:Spring Cloud Dalston 中文文档 参考手册 中文版
中文API文档:Spring Cloud Netflix 中文文档 参考手册 中文版
springCloud中国社区:http://springcloud.cn/
springCloud中文网:https://springcloud.cc
spring Boot | SPring Cloud | 关系 |
---|---|---|
1.2.x | Angle版本 | 兼容Spring Boot 1.2.x |
1.3.x | Brixton版本 | 兼容spring Boot 1.3.x 1.4.x |
1.4.x | Camden版本 | 兼容spring Boot 1.4.x 1.5.x |
1.5.x | Dalston | 1.5.x 不兼容2.0.x |
1.5.x | Edgware | 1.5.x 不兼容2.0.x |
2.0.x | Finchley | 兼容2.0.x 不兼容1.5.x |
2.1.x | Greenwich | |
2.2.x | Hoxton.SR12 | 2.2.0 — 2.4.0 |
2.4.x | 2020.0.5 | 2.4.0 — 2.6.0 |
2.6.x | 2021.0.0 | 2.6.1 — 2.6.4 |
父工程:导入依赖
<packaging>pompackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<junit.version>4.12junit.version>
<lombok.version>1.18.24lombok.version>
properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Hoxton.SR12version>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>2.3.1.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.29version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.2.0version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.11version>
dependency>
dependencies>
dependencyManagement>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
package com.liu.springCloud.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@NoArgsConstructor
@Accessors(chain = true) //支持链式写法
public class Dept implements Serializable {
//Dept实体类 orm 类表关系映射
private Long deptno; //主键自增不用写
private String dname;
//这个数据存在哪个数据库的字段 一个服务对应一个数据库,同一个信息可能存在不同的数据库
private String db_source; //自动生成
public Dept(String dname) {
this.dname = dname;
}
}
子模块中的依赖配置:
<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-01artifactId>
<groupId>com.liugroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>springcloud-01-apiartifactId>
<dependencies>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
dependencies>
project>
导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eurekaartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>com.liugroupId>
<artifactId>springcloud-01-apiartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jettyartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
dependencies>
application.yaml
server:
port: 8081
mybatis:
type-aliases-package: com.liu.springCloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
application:
name: springcloud-provider-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456789
#eureka的配置:服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
mybatis-config.xml
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>
<typeAliases>
<package name="com.liu.pojo"/>
typeAliases>
configuration>
mapper接口
@Mapper
@Repository
public interface DeptDao {
public boolean addDept(Dept dept);
public Dept queryById(Long id);
public List<Dept> queryAll();
}
mapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liu.springcloud.dao.DeptDao">
<insert id="addDept" parameterType="Dept">
insert into db01.dept(dname, db_source)
values (#{dname},#{db_source});
insert>
<select id="queryById" resultType="Dept" parameterType="Long">
select *
from db01.dept where deptno = #{deptno};
select>
<select id="queryAll" resultType="Dept">
select *
from db01.dept;
select>
mapper>
service层
public interface DeptService {
public boolean addDept(Dept dept);
public Dept queryById(Long id);
public List<Dept> queryAll();
}
service实现类
@service
public class DeptServiceImpl implements DeptService{
@Autowired
public DeptDao deptDao;
@Override
public boolean addDept(Dept dept) {
return deptDao.addDept(dept);
}
@Override
public Dept queryById(Long id) {
return deptDao.queryById(id);
}
@Override
public List<Dept> queryAll() {
return deptDao.queryAll();
}
}
controller层
//提供restful服务
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@PostMapping("/dept/add")
public Boolean addDept(@RequsetBody Dept dept){
boolean b = deptService.addDept(dept);
return b;
}
@GetMapping("/dept/query/{id}")
public Dept queryById(@PathVariable("id")Long id){
Dept dept = deptService.queryById(id);
return dept;
}
@GetMapping("/dept/list")
public List<Dept> queryAll(){
List<Dept> deptList = deptService.queryAll();
return deptList;
}
}
启动类
package com.liu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//启动类
@SpringBootApplication
@EnableEurekaClient //自动在服务启动后自动注册到eureka中
public class DeptProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_8001.class,args);
}
}
第三个微服务:springcloud-consumer-dept-80 消费者
导入依赖
<dependencies>
<dependency>
<groupId>com.liugroupId>
<artifactId>springcloud-01-apiartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
dependencies>
application.yaml
server:
port: 80
手动注入RestTemplate,config目录下自建
@Configuration
public class ConfigBean {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
controller
package com.liu.springcloud.controller;
import com.liu.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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
public class DeptConsumerController {
//消费者不应该有service层
//RestTemplate:有许多方法之间调用
//(url,实体:map,Class responseType)
@Autowired
private RestTemplate restTemplate; //提供多种便捷访问远程http服务的方法,简单restful服务模板
private static final String REST_URL_PREFIX = "http://localhost:8001";
@RequestMapping("/consumer/dept/query/{id}")
private Dept dept(@PathVariable("id") Long id) {
return restTemplate.getForObject(REST_URL_PREFIX + "dept/query/" + id, Dept.class);
}
@RequestMapping("/consumer/dept/add")
public Boolean add(Dept dept){
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
}
@RequestMapping("/consumer/dept/list")
public List<Dept> list(){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class);
}
}
启动类
@SpringBootApplication
public class DeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer_80.class,args);
}
}
什么是Eureka?
原理讲解
导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eureka-serverartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
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: #监控页面
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
启动类
@SpringBootApplication
@EnableEurekaServer //服务端的启动类,可以接收别人注册进来
public class EurekaServer_7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaServer_7001.class,args);
}
}
替换名字:
#eureka的配置:服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
instance:
instance-id: springcloud-provider-dept8001 #修改eureka上的默认信息
配置里面的信息:
1.导包
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eurekaartifactId>
<version>1.4.6.RELEASEversion>
dependency>
2.配置(基本不在这儿配置)
#info配置
info:
app.name: liuxiang-springcloud
company.name: blog.liu.study
3.结果
查看application的信息:
1.写controller
@Autowired
private DiscoveryClient client;
//注册进来的微服务 获取一些信息
@GetMapping("/dept/discovery")
public Object discovery(){
//获得微服务的列表清单
List<String> services = client.getServices();
System.out.println("discovery=>service"+services);
//得到一个具体的微服务信息
List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
for (ServiceInstance instance : instances) {
System.out.println(instance.getHost()+"\t"
+instance.getPort()
+"\t"+instance.getUri());
}
return this.client;
}
2.启动类添加注解
//启动类
@SpringBootApplication
@EnableEurekaClient //自动在服务启动后自动注册到eureka中
@EnableDiscoveryClient //服务发现
public class DeptProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_8001.class,args);
}
}
3.结果
4.后台显示
自我保护机制:
默认情况下,eurekaServer在一定事件内页面收到微服务的心跳,则会注销该实例(默认90s),当网络分区故障发生时,微服务与eureka之间无法正常通信,eureka通过自我保护机制解决,这种模式下,eureka会保护服务注册表的信息,不再删除注册表中的数据,网络恢复后,自动退出自我保护机制。
互相绑定,一个服务崩了,可以去访问另外的服务
在本机C:\Windows\System32\drivers\etc下做域名映射!
7001配置
server:
port: 7001
#eureka配置
eureka:
instance:
hostname: eureka7001.com #eureka服务端的实例名称
client:
register-with-eureka: false #表示是否向eureka注册中心注册自己
fetch-registry: false #如果为false则表示自己为注册中心
service-url:
#单机下
#集群下:关联
defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
7002
server:
port: 7002
#eureka配置
eureka:
instance:
hostname: eureka7002.com #eureka服务端的实例名称
client:
register-with-eureka: false #表示是否向eureka注册中心注册自己
fetch-registry: false #如果为false则表示自己为注册中心
service-url: #监控页面
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/
7003
server:
port: 7003
#eureka配置
eureka:
instance:
hostname: eureka7003.com #eureka服务端的实例名称
client:
register-with-eureka: false #表示是否向eureka注册中心注册自己
fetch-registry: false #如果为false则表示自己为注册中心
service-url: #监控页面
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
提供者发布到集群上,配置
server:
port: 8001
mybatis:
type-aliases-package: com.liu.springcloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
application:
name: springcloud-provider-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456789
#eureka的配置:服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: springcloud-provider-dept8001 #修改eureka上的默认信息
#info配置
info:
app.name: liuxiang-springcloud
company.name: blog.liu.study
回顾CAP原则
RDBMS(mYSQL,Oracle,sqlServer) ==> ACID
NoSQL(redis,mongdb) ==> CAP
ACID:
CAP:
CAP理论的核心:
一个分布式系统不可能同时满足C一致性,A可用性,P容错性
牺牲了可用性,所以是CP原则!
当向注册中心查询服务列表时候,可用容忍注册中心返回的几分钟以前的注册信息,但不能接收服务直接down掉不可用。服务注册功能对可用性的要求高于一致性。但是zk会出现一种情况,当master节点因为网络问题与其他节点失去联系,剩余节点会重新进行leader选举。问题在于,选举leader的时间过长,30s-120s,且选举期间整个zk集群都是不可用的,这就导致在选举期间注册服务瘫痪。
**eureka各个节点都是平等的。几个节点挂了不会影响正常节点的工作,剩余节点依然可用提供注册和查询功能。**自我保护机制:
1.eureka不再从注册表中移除因为长时间没收到心跳而应该过期的服务
2.仍然能够接收新服务的注册和查询请求,但是不会被同步到其他节点上
3.当网络稳定时,当前实例新的的注册信息会被同步到其他节点中
ribbon是什么?
ribbon能干嘛?
负载均衡:将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)
常用的负载均衡软件:Nginx,Lvs等
dubbo,springCloud中均提供负载均衡,springCloud的负载均衡算法可用自定义
负载均衡简单分类:
导入依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-ribbonartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eurekaartifactId>
<version>1.4.6.RELEASEversion>
dependency>
配置:
server:
port: 80
#eureka配置
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
启动类加注解使其生效
@SpringBootApplication
@EnableEurekaClient
public class DeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer_80.class,args);
}
}
自定义restTemplate的配置,使其变成负载均衡的
@Configuration
public class ConfigBean {
//配置负载均衡实现restTemplate
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
在客户端消费者的controller
//通过ribbon的时候,这里的地址应该是一个变量,通过服务id去访问
// private static final String REST_URL_PREFIX = "http://localhost:8001";
private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
在springcloud同级目录下建包
@Configuration
public class LiuRule {
//配置负载均衡实现restTemplate
//IRule
//AvailabilityFilteringRule:会先过滤跳闸,崩溃的服务,对剩下的服务进行轮询
//RoundRobinRule 轮询
//RandomRule 随机
//RetryRule重试
@Bean
public IRule myRule(){
return new RandomRule();
}
}
启动类下:在微服务启动时候就加载自定义类
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = LiuRule.class)
public class DeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer_80.class,args);
}
}
feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,蕾仕于controller调用service,springCloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端
只需要创建一个接口,如何添加注解即可!
访问微服务的两种方法:
使用ribbon+restTemplate,利用restTemplate对http请求的封装处理,形成了一套模板化的调用方法。但在实际开发中,由于对服务依赖的调用不止一处,往往一个接口会被多出调用,所以通常都会针对每个欸服务自行封装一些客户端类来包装这些依赖服务的调用。
在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它(类似于Dao接口上标注Mapper注解,现在是一个微服务接口上面标注一个Feign注解即可)
导入依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-feignartifactId>
<version>1.4.6.RELEASEversion>
dependency>
api层写service接口供其他服务访问
@Component
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
@GetMapping("/dept/query/{id}")
public Dept queryById(@PathVariable("id")Long id);
@GetMapping("/dept/list")
public List<Dept> queryAll();
@PostMapping("/dept/add")
public boolean addDept(Dept dept);
}
消费者Controller层:通过注解实现
package com.liu.springcloud.controller;
import com.liu.springcloud.pojo.Dept;
import com.liu.springcloud.service.DeptClientService;
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 javax.annotation.Resource;
import java.util.List;
@RestController
public class DeptConsumerController {
@@Resource
private DeptClientService service = null;
@RequestMapping("/consumer/dept/query/{id}")
private Dept dept(@PathVariable("id") Long id) {
return this.service.queryById(id);
}
@RequestMapping("/consumer/dept/add")
public Boolean add(Dept dept){
return this.service.addDept(dept);
}
@RequestMapping("/consumer/dept/list")
public List<Dept> list(){
return this.service.queryAll();
}
}
实现类:加上注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.liu.springcloud"})
public class FeignDeptConsumer {
public static void main(String[] args) {
SpringApplication.run(FeignDeptConsumer.class,args);
}
}
结果:本质还是通过eureka,通过注解,让代码的可读性变强!
官方文档翻译网址:Hystrix 使用手册 | 官方文档翻译 - 闪客sun - 博客园 (cnblogs.com)
完成情况好的请求流如下:
当一个依赖的节点坏掉时,将阻塞整个的用户请求:
流量高峰时,一个单节点的宕机或延迟,会迅速导致所有服务负载达到饱和。应用中任何一个可能通过网络访问其他服务的节点,都有可能成为造成潜在故障的来源。更严重的是,还可能导致服务之间的延迟增加,占用队列、线程等系统资源,从而导致多系统之间的级联故障。
所有上述表现出来的故障或延迟,都需要一套管理机制,将节点变得相对独立,这样任何一个单节点故障,都至少不会拖垮整个系统的可用性。
多个微服务之间调用的时候,假设微服务A调用B和C,B和C又调用其他的微服务,这就是所谓的"扇出",如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃就是所谓的"雪崩效应"。
在分布式环境中,不可避免地会遇到所依赖的服务挂掉的情况,Hystrix 可以通过增加 延迟容忍度 与 错误容忍度,来控制这些分布式系统的交互。Hystrix 在服务与服务之间建立了一个中间层,防止服务之间出现故障,并提供了失败时的备选响应( fallback) 策略,来增加系统的整体可靠性和弹性,而不是长时间的等待或者抛出调用方法无法处理的异常,这样就保证了服务调用方的线程不会长时间占用。
用处:
当扇出链路的某个微服务不可用或者响应时间太长,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测该节点微服务调用响应正常后回复调用链路。
导入依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-hystrixartifactId>
<version>1.4.6.RELEASEversion>
dependency>
服务提供方controller层
//提供restful服务
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping("/dept/query/{id}")
@HystrixCommand(fallbackMethod = "hystrixGet")
public Dept queryById(@PathVariable("id")Long id){
Dept dept = deptService.queryById(id);
if (dept==null){
throw new RuntimeException("id=>"+id+" 不存在该用户,信息无法找到!");
}
return dept;
}
//备选方法
public Dept hystrixGet(@PathVariable("id")Long id){
return new Dept().setDeptno(id)
.setDname("id=>"+id+" 不存在该用户,信息无法找到!@Hystrix")
.setDb_source("no this database in MySQL");
}
}
启动类:添加对熔断的支持
@SpringBootApplication
@EnableEurekaClient //自动在服务启动后自动注册到eureka中
@EnableDiscoveryClient //服务发现
@EnableHystrix //包含了@EnableCircuitBreaker
public class DeptProviderHystrix_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProviderHystrix_8001.class,args);
}
}
提供者配置:可用显示ip prefer-ip-address: true
#eureka的配置:服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: springcloud-provider-dept8001 #修改eureka上的默认信息
prefer-ip-address: true
api的service层
@Component
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService {
@GetMapping("/dept/query/{id}")
public Dept queryById(@PathVariable("id")Long id);
@GetMapping("/dept/list")
public List<Dept> queryAll();
@PostMapping("/dept/add")
public boolean addDept(Dept dept);
}
api的service层的fallback工厂服务降级
package com.liu.springcloud.service;
import com.liu.springcloud.pojo.Dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;
//降级
@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory {
@Override
public DeptClientService create(Throwable throwable) {
return new DeptClientService() {
@Override
public Dept queryById(Long id) {
return new Dept().setDeptno(id)
.setDname("id=>"+id+"没有对应的信息,客户端提供了降级的信息,整个服务现在已经关闭")
.setDb_source("no source");
}
@Override
public List<Dept> queryAll() {
return null;
}
@Override
public boolean addDept(Dept dept) {
return false;
}
};
}
}
客户端的配置:开启降级
server:
port: 80
#eureka配置
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
#开启降级
feign:
hystrix:
enabled: true
关闭服务提供者8001,结果:
服务熔断:代码写在提供方,相当于处理、返回异常
服务降级:代码写在消费方,提供方关闭服务后,提示、返回异常信息
建立工程:springcloud-consumer-hystrix-dashboard
导入依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-hystrixartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-hystrix-dashboardartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-hystrixartifactId>
<version>1.4.6.RELEASEversion>
dependency>
配置application.yaml
server:
port: 9001
hystrix:
dashboard:
proxy-stream-allow-list: localhost
启动类
package com.liu.springcloud;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
//启动类
@SpringBootApplication
@EnableEurekaClient //自动在服务启动后自动注册到eureka中
@EnableDiscoveryClient //服务发现
@EnableHystrix
public class DeptProviderHystrix_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProviderHystrix_8001.class,args);
}
//增加一个dashboard的bean
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
registrationBean.addUrlMappings("/actuator/hystrix.stream");
return registrationBean;
}
}
要保证服务提供方有监控信息的依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
结果:localhost:9001/hystrix
先发起一起query请求,访问localhost:8001/actuator/hystrix.stream,会有data数据产生
再到Hystrix Monitor,进行监控!
一直loading解决方法:
hystrix:
dashboard:
proxy-stream-allow-list: localhost
什么是zuul?
官方文档:Spring Cloud Netflix 中文文档 参考手册 中文版
导入配置:
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-zuulartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-hystrixartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-hystrix-dashboardartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-ribbonartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eurekaartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>com.liugroupId>
<artifactId>springcloud-01-apiartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
dependencies>
配置:实现路由加过滤
server:
port: 9527
spring:
application:
name: springcloud-zuul
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: zuul9527.com
prefer-ip-address: true
info:
app.name: liu-springcloud
company.name: blog.liu.com
zuul:
routes:
mydept.serviceId: springcloud-provider-dept
mydept.path: /mydept/**
ignored-services: springcloud-provider-dept #不能再使用这个路径访问了
启动类:@EnableZuulProxy
@SpringBootApplication
@EnableZuulProxy
public class zuulApplication_9527 {
public static void main(String[] args) {
SpringApplication.run(zuulApplication_9527.class,args);
}
}
访问此网址可用得到结果:localhost:9527/mydept/dept/query/1
配置后,实现过滤操作,访问localhost:9527/springcloud-provider-dept/dept/query/1,结果不存在
微服务意味着要将单体应用中的业务拆分成一个个子服务,每个服务的力度较小,因此系统中会出现大量的服务,由于每个服务都需要必要的配置信息才能运行,所以一套集中式的,动态的配置管理设施。
springcloud提供configServer解决这个问题!
为微服务架构中的微服务提供集中化的外部配置支持,配置服务器为各个不同微服务应用的所有环节提供一个中心化的外部配置
springcloud config分为服务端和客户端两部分:
服务端:分布式配置中心,是一个独立的微服务应用,用来连接配置服务器并未客户端提供获取配置信息,加密,解密信息等访问接口
客户端:则是通过指定的配置中心来管理应用资源,以及与业务相关的配置内容,并启动的时候从配置中心获取和加载信息,配置服务器默认采用git来存储配置信息,这样有助于对环境配置进行版本管理。
1.从gitee上拷贝地址
2.生成公钥
会在本机C:\Users\liuxiang.ssh处生成两个文件:.pub是公钥
放入gitee上面的公钥处即可!
3.在本地建立一个文件夹存放代码,打开Git客户端右键 Git Bash here,输入命令
git clone + 复制的地址
:shift+ins复制键
5.四步上传至远程仓库
# 添加文件
git add .
# 查看状态
git status
# 提交到本地仓库 提交和消息
git commit -m "first commit"
#push到远程仓库
git push origin master
导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-config-serverartifactId>
<version>2.2.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
配置
server:
port: 3344
spring:
application:
name: springcloud-config-server
#连接远程仓库
cloud:
config:
server:
git:
uri: https://gitee.com/lxxdyy12138/springcloud-config.git
启动类:
@SpringBootApplication
@EnableConfigServer
public class Config_Server_3344 {
public static void main(String[] args) {
SpringApplication.run(Config_Server_3344.class,args);
}
}
访问:localhost:3344/application-dev.yaml
建立一个config-client文件,将其push到远程仓库上!
导入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-configartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
配置:bootstrap.yaml
#系统级别的配置
spring:
cloud:
config:
uri: http://localhost:3344
name: config-client #需要从git上读取的资源名称,不需要后缀
profile: dev
label: master
application.yaml
#用户级别的配置
spring:
application:
name: springcloud-config-client-3355
启动类
@SpringBootApplication
public class ConfigClient_3355 {
public static void main(String[] args) {
SpringApplication.run(ConfigClient_3355.class,args);
}
}
测试类controller
@RestController
public class ConfigController {
@Value("${spring.application.name}")
private String applicationName;
@Value("${eureka.client.service-url.defaultZone}")
private String eurekaServer;
@Value("${server.port}")
private String port;
@RequestMapping("/config")
public String getConfig(){
return "applicationName:"+applicationName+
"eurekaServer"+eurekaServer+
"port"+port;
}
}
结果访问:
建立远程仓库配置文件:
spring:
profiles:
active: dev
---
server:
port: 7001
spring:
profiles: dev
application:
name: springcloud-config-eureka
#eureka配置
eureka:
instance:
hostname: eureka7001.com #eureka服务端的实例名称
client:
register-with-eureka: false #表示是否向eureka注册中心注册自己
fetch-registry: true #如果为false则表示自己为注册中心
service-url:
#单机下
#集群下:关联
defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
---
server:
port: 7001
spring:
profiles: test
application:
name: springcloud-config-eureka
#eureka配置
eureka:
instance:
hostname: eureka7001.com #eureka服务端的实例名称
client:
register-with-eureka: false #表示是否向eureka注册中心注册自己
fetch-registry: true #如果为false则表示自己为注册中心
service-url:
#单机下
#集群下:关联
defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
spring:
profiles:
active: dev
---
server:
port: 8001
mybatis:
type-aliases-package: com.liu.springcloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
profiles: dev
application:
name: springcloud-config-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456789
#eureka的配置:服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: springcloud-config-dept8001 #修改eureka上的默认信息
prefer-ip-address: true
#info配置
info:
app.name: liuxiang-springcloud
company.name: blog.liu.study
---
server:
port: 8002
mybatis:
type-aliases-package: com.liu.springcloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
profiles: test
application:
name: springcloud-config-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456789
#eureka的配置:服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: springcloud-config-dept8001 #修改eureka上的默认信息
prefer-ip-address: true
#info配置
info:
app.name: liuxiang-springcloud
company.name: blog.liu.study
push到远程仓库
导包
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-configartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eureka-serverartifactId>
<version>1.4.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
dependencies>
配置:
bootstrap.yaml
spring:
cloud:
config:
name: config-eureka #这里的名字是远程仓库项目的名字
label: master
profile: dev
uri: http://localhost:3344 #服务器访问远程仓库的地址
application.yaml
spring:
application:
name: springcloud-config-eureka_7001
server:
port: 8002
mybatis:
type-aliases-package: com.liu.springcloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
profiles: test
application:
name: springcloud-config-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456789
#eureka的配置:服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: springcloud-config-dept8001 #修改eureka上的默认信息
prefer-ip-address: true
#info配置
info:
app.name: liuxiang-springcloud
company.name: blog.liu.study
push到远程仓库
[外链图片转存中...(img-rczTYae2-1658915772501)]
导包
```xml
org.springframework.cloud
spring-cloud-starter-config
org.springframework.cloud
spring-cloud-starter-eureka-server
1.4.6.RELEASE
org.springframework.boot
spring-boot-devtools
配置:
bootstrap.yaml
spring:
cloud:
config:
name: config-eureka #这里的名字是远程仓库项目的名字
label: master
profile: dev
uri: http://localhost:3344 #服务器访问远程仓库的地址
application.yaml
spring:
application:
name: springcloud-config-eureka_7001