spring Cloud是一个基于Spring Boot实现的微服务架构开发工具。它为微服务架构中涉及的服务治理、断路器、负载均衡、配置管理、控制总线和集群状态管理等操作提供了一种简单的开发方式。
- 外部或者内部的非Spring Cloud项目都统一通过API网关(Zuul)来访问内部服务。
- 网关接收到请求后,从注册中心(Eureka)获取可用服务。
- 由Ribbon进行均衡负载后,分发到后端的具体实例。
- 微服务之间通过Feign进行通信处理业务。
- Hystrix负责处理服务超时熔断。
- Turbine监控服务间的调用和熔断相关指标。
配置中心管理各微服务不同环境下的配置文件。
spring cloud官网
spring cloud中文网
spring cloud中文社区
spring cloud与spring boot兼容性介绍
官网介绍网址
如果没有对应版本,项目就可能会报错
服务拆分注意事项
- 不同微服务,不要重复开发相同业务
- 微服务数据独立,不要访问其它微服务的数据库
- 微服务可以将自己的业务暴露为接口,供其它微服务调用
RestTemplate 是 spring 发起请求的中间件,在没用使用注册中心时使用这个,有注册中心时使用Feign比较好
- 在启动类里配置注入 RestTemplate
@SpringBootApplication public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } @Bean RestTemplate restTemplate() { return new RestTemplate(); } } - 调用 RestTemplate 发起请求
get 请求用 getForEntity,post 请求用 postForEntityservice public class OrderService { @Autowired private RestTemplate restTemplate; public Order queryOrderById (Long orderId) { //1.查询订单 Order order = orderMapper.findById(orderId); // TOD0 2.查询用户 String url = "http://localhost:8081/usep/" +order.getUserId(); //第二个参数默认是json,填了会反序列化成User类型 User user = restTemplate.getFor0bject(url, User.class); //3.封装user 信息 order.setUser(user); //4.返回 return order; } }
提供者(provide)与消费者(consumer)
服务提供者:一次业务中,被其它微服务调用的服务。(提供接口给其它微服务)
服务消费者:一次业务中,调用其它微服务的服务。(调用其它微服务提供的接口)
提供者与消费者角色其实是相对的
一个服务可以同时是服务提供者和服务消费者
父级工程的pom.xml
创建提供者(provide)子工程user-provide4.0.0 org.liu springcloud-parent pom 1.0-SNAPSHOT user-provider user-provider-demo01 user-consumer eureka-server Hoxton.SR1 spring-boot-starter-parent org.springframework.boot 2.2.2.RELEASE org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import
在父级工程springcloud-parent下创建提供者(provide)的maven子工程user-provide
pom.xml
springcloud-parent org.liu 1.0-SNAPSHOT 4.0.0 user-provider org.springframework.boot spring-boot-starter-web
server: port: 18081
启动类
package com.liu.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProviderApplication{
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class,args);
}
}
controller层
package com.liu.provider.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/find/{id}")
public String userFind(@PathVariable(value = "id") String id){
return "我是提供者(provide)的/user/find,传过来的id是"+id;
}
}
创建提供者(consumer)子工程user-consumer
在父级工程springcloud-parent下创建消费者(consumer)的maven子工程user-consumer
pom.xml
springcloud-parent org.liu 1.0-SNAPSHOT 4.0.0 user-provider org.springframework.boot spring-boot-starter-web
配置文件application.yml
server: port: 18082
启动类
package com.liu.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProviderApplication{
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class,args);
}
}
controller层
package com.liu.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/consumer")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/id")
public String userFind(@PathVariable(value = "id") String id){
String url="http://127.0.0.1:18081/user/find/"+id;
return restTemplate.getForObject(url,String.class);
}
}
这用访问http://127.0.0.1:18082/consumer/id就可以访问到提供者(consumer)的内容
小结- 服务消费者使用RestTemplate调用服务提供者,使用RestTemplate调用的时候,需要先创建并注入到SpringlOC容器中
- 在服务消费者中,我们把url地址硬编码到代码中,不方便后期维护
- 在服务消费者中,不清楚服务提供者的状态(user-provider有可能没有宕机了)
- 服务提供者只有一个服务,即便服务提供者形成集群,服务消费者还需要自己实现负载均衡
- 服务提供者的如果出现故障,不能及时发现。
eureka的作用
- 消费者该如何获取服务提供者具体信息?
- 服务提供者启动时向eureka注册自己的信息eureka保存这些信息
- 消费者根据服务名称向eureka拉取提供者信息
- 如果有多个服务提供者,消费者该如何选择?
- 服务消费者利用负载均衡算法,从服务列表中挑选一个
- 消费者如何感知服务提供者健康状态?
- 服务提供者会每隔30秒向EurekaServer发送心跳请求,报告健康状态eureka会更新记录服务列表信息,心跳不正常会被剔除
- 消费者就可以拉取到最新的信息
总结
在Eureka架构中,微服务角色有两类:
- EurekaServer:服务端,注册中心()
- 记录服务信息
- 心跳监控
- EurekaClient:客户端
- Provider:服务提供者,例如案例中的user-provider
- 注册自己的信息到EurekaServer
- 每隔30秒向EurekaServer发送心跳
- Consumer:服务消费者,例如案例中的 user-consumer
- 根据服务名称从EurekaServer拉取服务列表
- 基于服务列表做负载均衡,选中一个微服务后发起远程调用
- Provider:服务提供者,例如案例中的user-provider
在父级工程springcloud-parent下创建eureka-server子项目
pom.xml
springcloud-parent org.liu 1.0-SNAPSHOT 4.0.0 eureka-server org.springframework.cloud spring-cloud-starter-netflix-eureka-server
application.yml配置文件
server:
port: 7001
# 给注册中心起名字
spring:
application:
name: eureka-server
# 暴露地址给提供者和消费者找到
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:7001/eureka # EurekaServer的地址
fetch-registry: false # 是否从数据中心拉取数据
register-with-eureka: false # 是否需要把自己添加到注册中心
启动类
package com.liu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer //表示启动 Eureka 服务器
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,args);
}
}
启动服务,在网页输入127.0.0.1:7001这就算搭建成功了
我们的user-provider属于服务提供者,需要在(user-provider工程中引入Eureka客户端依赖,然后在配置文件中指定Eureka服务地址,然后在启动类中开启Eureka服务发现功能。
user-provider的pom.xml
springcloud-parent org.liu 1.0-SNAPSHOT 4.0.0 user-provider org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client
在启动类里加启动eureka客户端注解
package com.liu.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableDiscoveryClient //启动 Eureka 客户端
public class ProviderApplication{
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class,args);
}
}
配置文件
server:
port: 18081
spring:
application:
name: user-provider
eureka:
client:
register-with-eureka: true # 是否需要把自己添加到注册中心
service-url:
defaultZone: http://127.0.0.1:7001/eureka # EurekaServer的地址
注册进去了
user-consumer的pom.xml
springcloud-parent org.liu 1.0-SNAPSHOT 4.0.0 user-consumer org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client
在启动类里加启动eureka客户端注解
package com.liu.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient //启动 Eureka 客户端
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
配置文件
server:
port: 18082
spring:
application:
name: user-consumer
eureka:
client:
register-with-eureka: true # 是否需要把自己添加到注册中心
service-url:
defaultZone: http://127.0.0.1:7001/eureka # EurekaServer的地址
也注册成功了
现在可以动态获取在 Eureka注册中心上 提供者的地址了,消费者的controller层
package com.liu.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
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
@RequestMapping("/consumer")
public class UserController {
@Autowired
private RestTemplate restTemplate;
// 解决硬编码
// 服务发现,用来动态获取 Eureka服务器 上注册的 应用
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping("/{id}")
public String userFind(@PathVariable(value = "id") String id){
// String url="http://127.0.0.1:18081/user/find/"+id;
// 通过 discoveryClient.getInstances 拿到 user-provider 应用的信息
// list类型是因为 负载均衡 要求 应用名都得一样
List list = discoveryClient.getInstances("user-provider");
ServiceInstance serviceInstance = list.get(0);
String url = "http://" + serviceInstance.getHost() + ":" +serviceInstance.getPort() + "/user/find/"+id;
return restTemplate.getForObject(url,String.class);
}
}
也是成功的
Spring Cloud Ribbon是一个基于Http和TCP的客户端负载均衡工具,Ribbon主要解决集群服务中,多个服务高效率访问的问题。
负载均衡在系统架构中是一个非常重要,并且是不得不去实施的内容。因为负载均衡是对系统的高可用、网络压力的缓解和处理能力扩容的重要手段之一。
客户端与服务端级别的负载均衡
- 服务器端负载均衡∶传如Nginx,通过Nginx进行负载均衡过程如下:先发送请求给nginx服务器,然后通过负载均衡算法,在多个业务服务器之间选择一个进行访问;即在服务器端再进行负载均衡算法分配。
- 客户端负载均衡︰客户端会有一个服务器地址列表,在发送请求前通过负载均衡算法选择一个服务器,然后进行访问,即在客户端就进行负载均衡算法分配。
只需要在消费者user-consumer上的RestTemplate添加注解@LoadBalanced就可以了
package com.liu.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient //启动 Eureka 客户端
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
@LoadBalanced // 负载均衡注解
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
再修改一下请求路径
package com.liu.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
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
@RequestMapping("/consumer")
public class UserController {
@Autowired
private RestTemplate restTemplate;
// 服务发现,用来动态获取 Eureka服务器 上注册的 应用
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping("/{id}")
public String userFind(@PathVariable(value = "id") String id){
// String url="http://127.0.0.1:18081/user/find/"+id;
// 通过 discoveryClient.getInstances 拿到 user-provider 应用的信息
// list类型是因为 负载均衡 要求 应用名都得一样
// List list = discoveryClient.getInstances("user-provider");
// ServiceInstance serviceInstance = list.get(0);
//
// String url = "http://" + serviceInstance.getHost() + ":" +serviceInstance.getPort() + "/user/find/"+id;
String url="http://user-provider/user/find/"+id;
return restTemplate.getForObject(url,String.class);
}
}
我们复制user-provider项目,并改名为user-provider-demo01项目
user-provider-demo01的application.yml只修改端口号,这样我们就有两个叫 user-provider的应用了
server:
port: 18083
spring:
application:
name: user-provider
eureka:
client:
register-with-eureka: true # 是否需要把自己添加到注册中心
service-url:
defaultZone: http://127.0.0.1:7001/eureka # EurekaServer的地址
再修改一下请求方法
package com.liu.provider.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/find/{id}")
public String userFind(@PathVariable(value = "id") String id){
return "我是提供者(provide-demo01)的/user/find,传过来的id是"+id;
}
}
访问http://127.0.0.1:18082/consumer/1,然后再次刷新,就可以看到不一样的内容出现
有一条山路,被山洪冲垮了,但是大家都不知道。车辆还是沿着山路前进,直到被挡住了去路才发现此路不通,但是此时路上车太多了,前面的车走不了也退不回来,后面的车还在源源不断的开过来,所有人都挤在山上不能动。后来有人就制作了一个提示牌―—“此路不通,车辆绕行"。以后每次山路被冲毁的时候,都把这块牌子立在山脚,来往的车辆—看见这牌子就掉头回去了。
这块牌子就是一个断路器,这条山路就是一个服务组件。平时服务组件正常访问的时候断路器不发挥作用,但是一旦服务组件运转异常,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。断路器的作用就显现出来了,断路打开后,可用避免连锁故障,fallback方法可以直接返回一个固定值。
Hystrix,英文意思是豪猪,全身是刺,刺是一种保护机制。Hystrix也是Netflix公司的一款组件。Hystrix的作用是什么?︰实现服务熔断降级处理,保护微服务,防止雪崩效应发生。
Hystri是Neflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库、防止出现级联失败也就是雪崩效应。
雪崩效应
对于同步调用,当库存服务不可用时,商品服务请求线程被阻塞,当有大批量请求调用库存服务时,最终可能导致整个商品服务资源耗尽,无法继续对外提供服务。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成不可估量的严重后果,这就是常说的服务故障的"雪崩效应“。
熔断器状态机有3个状态:
熔断器有三个状态CLOSED、OPEN、HALF_OPEN熔断器默认关闭状态,当触发熔断后状态变更为OPEN,在等待到指定的时间,Hystrix会放请求检测服务是否开启,这期间熔断器会变为HALF_OPEN半开启状态,熔断探测服务可用则继续变更为CLOSED关闭熔断器。
Closed:关闭状态,所有请求正常访问
Open:打开状态,所有请求都会被降级。
Hystrix会对请求情况计数,当一定时间失败请求百分比达到阈(yu:四声)值(极限值),则触发熔断,断路器完全关闭,默认失败比例的阈值是50%,请求次数最低不少于20次
Half Open:半开状态
Open状态不是永久的,打开一会后会进入休眠时间(默认5秒)。休眠时间过后会进入半开状态。
半开状态:熔断器会判断下一次请求的返回状况,如果成功,熔断器切回closed状态。如果失败,熔断器切回open状态。
使用
在user-consumer项目里加入熔断器
在pom.xml引入坐标
springcloud-parent org.liu 1.0-SNAPSHOT 4.0.0 user-consumer org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-netflix-hystrix
在启动类里开启
package com.liu.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient //启动 Eureka 客户端
@EnableCircuitBreaker // 开启熔断器
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
在控制器里使用,局部使用(方法上面)
package com.liu.consumer.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
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
@RequestMapping("/consumer")
public class UserController {
@Autowired
private RestTemplate restTemplate;
// 服务发现,用来动态获取 Eureka服务器 上注册的 应用
@Autowired
private DiscoveryClient discoveryClient;
// 服务宕机时,回调函数返回数据告诉调用方出错了
public String fallback(){
return "宕机了!!";
}
@RequestMapping("/{id}")
@HystrixCommand(fallbackMethod = "fallback") //熔断器
public String userFind(@PathVariable(value = "id") String id){
// String url="http://127.0.0.1:18081/user/find/"+id;
// 通过 discoveryClient.getInstances 拿到 user-provider 应用的信息
// list类型是因为 负载均衡 要求 应用名都得一样
// List list = discoveryClient.getInstances("user-provider");
// ServiceInstance serviceInstance = list.get(0);
//
// String url = "http://" + serviceInstance.getHost() + ":" +serviceInstance.getPort() + "/user/find/"+id;
String url="http://user-provider/user/find/"+id;
return restTemplate.getForObject(url,String.class);
}
}
在控制器里使用,全局使用(类上面)
package com.liu.consumer.controller;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
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
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "fallback") //全局熔断器
public class UserController {
@Autowired
private RestTemplate restTemplate;
// 服务发现,用来动态获取 Eureka服务器 上注册的 应用
@Autowired
private DiscoveryClient discoveryClient;
// 服务宕机时,回调函数返回数据告诉调用方出错了
public String fallback(){
return "宕机了!!";
}
@RequestMapping("/{id}")
@HystrixCommand //熔断器
public String userFind(@PathVariable(value = "id") String id){
// String url="http://127.0.0.1:18081/user/find/"+id;
// 通过 discoveryClient.getInstances 拿到 user-provider 应用的信息
// list类型是因为 负载均衡 要求 应用名都得一样
// List list = discoveryClient.getInstances("user-provider");
// ServiceInstance serviceInstance = list.get(0);
//
// String url = "http://" + serviceInstance.getHost() + ":" +serviceInstance.getPort() + "/user/find/"+id;
String url="http://user-provider/user/find/"+id;
return restTemplate.getForObject(url,String.class);
}
}



