一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第2天,点击查看活动详情。
前言
Spring Cloud是一系列框架的集合。利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、消息总线、负载均衡、断路器、数据监控等,都可以用Spring Boot的开发风格做到一键启动和部署。这里我们会尝试利用spring Cloud的Eureka ,kafka,redis等分布式组件搭建一个处理好并发写(减库存),保证数据的最终一致性的秒杀系统demo。
注册中心 Eureka
Eureka 采用 CS(Client/Server,客户端/服务器) 架构,它包括以下两大组件:
- Eureka Server:Eureka 服务注册中心,主要用于提供服务注册功能。当微服务启动时,会将自己的服务注册到 Eureka Server。Eureka Server 维护了一个可用服务列表,存储了所有注册到 Eureka Server 的可用服务的信息,这些可用服务可以在 Eureka Server 的管理界面中直观看到。
- Eureka Client:Eureka 客户端,通常指的是微服务系统中各个微服务,主要用于和 Eureka Server 进行交互。在微服务应用启动后,Eureka Client 会向 Eureka Server 发送心跳。若 Eureka Server 在多个心跳周期内没有接收到某个 Eureka Client 的心跳,Eureka Server 将它从可用服务列表中移除。
注册中心 Eureka 能够确保各个服务的高可用性,以及他也是Spring cloud各个其他微服务组件的基础和重中之重。
配置以及代码
首先搭建一个空的spring boot 服务,然后在公用的服务中加入公用配置
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo</groupId>
<artifactId>spring-cloud</artifactId>
<version>0.0.1</version>
<name>spring-cloud</name>
<description>Demo project for Spring Boot</description>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
</properties>
<modules>
<module>eureka-server</module>
<module>eureka-client</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
公用的服务中配置server和client端两个 新加一个module server 在pom中添加eureka-server配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
然后添加yml 和启动类的注解
@EnableEurekaServer
spring:
application:
name: eureka-server
server:
port: 8081
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8081/eureka
fetch-registry: false
register-with-eur
新加一个module client
在pom中添加eureka-client配置 和yml的配置,设置service为刚刚配置的http://localhost:8081/eureka
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
spring:
application:
name: eureka-client
server:
port: 8082
eureka:
client:
service-url:
defaultZone: http://localhost:8081/eureka
然后在启动类加注解@EnableEurekaClient
启动以后直接在浏览器输入http://localhost:8081/
可以看到刚刚的这个服务已经注册上了
Hystrix
配置好Eureka就可以配置Hystrix来加强系统的稳定性,我们知道分布式服务的互相调用可能会导致一个服务的崩溃影响到很多其他的服务,也就是所谓的服务雪崩,一个服务的崩溃导致整个系统全面的崩溃。 那 Hystrix能做到那些措施呢:
- 服务降级
- 服务熔断
- 服务限流 首先我们引入Hystrix的依赖
Hystrix服务降级
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在启动类加入注解@EnableCircuitBreaker
在代码中加入服务降级相关的注解
//服务降级
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000") //3秒钟以内就是正常的业务逻辑
})
public String paymentInfo_TimeOut(Integer id) {
int timeNumber = 2;
try {
TimeUnit.SECONDS.sleep(timeNumber);
} catch (Exception e) {
e.printStackTrace();
}
return "线程池:" + Thread.currentThread().getName() + " paymentInfo_TimeOut,id: " + id + "\t" + "呜呜呜" + " 耗时(秒)" + timeNumber;
}
//兜底方法
public String paymentInfo_TimeOutHandler(Integer id) {
return "线程池:" + Thread.currentThread().getName() + " 系统繁忙, 请稍候再试 ,id: " + id + "\t" + "请求太多了";
}
启动服务测试降级 使用 JMeter压测接口 //todo JMeter 接口返回结果:
Hystrix服务熔断
在代码中加入HystrixCommand注解可以启用服务熔断机制
//服务熔断
@HystrixCommand(fallbackMethod = "circuitBreaker_fallback",commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间范围
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
})
public String circuitBreaker( Integer id){
if(id<1){
throw new RuntimeException("服务异常");
}
String serialNumber = String.valueOf(Math.random());
return Thread.currentThread().getName()+""+"调用成功,流水号:"+serialNumber;
}
public String circuitBreaker_fallback(@PathVariable("id") Integer id){
return "调用次数超过限制,请稍候再试 id: " +id;
}
正常的执行结果是:
熔断以后直接调用熔断的服务,起到保护下游服务的作用
Hystrix Dashboard 监控
新建一个moduleeureka-hystrix-dashboard用于监控
首先引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
启动类加入注解:@EnableHystrixDashboard
在配置中加入
spring:
application:
name: eureka-hystrix-dashboard
server:
port: 9001
hystrix:
dashboard:
proxy-stream-allow-list: localhost
在被监控的应用的启动类加入bean
@Bean
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
然后启动服务访问9001
输入我们刚刚配置的被监控的服务的地址和监控流。
然后调刚刚的应用就可以看到监控的数据发生变化