阿里云网站建设考试认证题,定制衣服,进出口贸易网站制作,地域性旅游网站建设系统结构✅作者简介#xff1a;大家好#xff0c;我是 Meteors., 向往着更加简洁高效的代码写法与编程方式#xff0c;持续分享Java技术内容。 #x1f34e;个人主页#xff1a;Meteors.的博客 #x1f49e;当前专栏#xff1a; Java微服务 ✨特色专栏#xff1a; 知识分享 大家好我是 Meteors., 向往着更加简洁高效的代码写法与编程方式持续分享Java技术内容。 个人主页Meteors.的博客 当前专栏 Java微服务 ✨特色专栏 知识分享 本文内容【2.1】Java微服务详解Hystrix ** ps ** 阅读这篇文章如果有问题或者疑惑欢迎各位在评论区提问或指出 ----------------------------------------------------- 目录 ---------------------------------------------------------
目录 一、基本介绍
1. 基本介绍
2. 实现原理
二、相关功能
1. 请求缓存
概述
缺点
Redis的方式
1) 导入依赖
2) 添加配置文件
3) 增加Redis 配置
4增加缓存注解
5) 接口实现类增加缓存注解
6结果
2. 请求合并实现
1). pom文件添加依赖
2). 在实现类进行请求合并
3开启熔断注解
4模拟同时发起多个请求
3.线程池隔离
1介绍
2优点
3缺点
4代码示例
4. 信号量隔离
1介绍
2代码示例
3) 线程池颗粒与信号隔离对比
5.服务熔断
1介绍
2调用 其他 参考文献 --------------------------------------------------------------------------------------------------------------------------------- 一、基本介绍 1. 基本介绍 Hystix是一个延迟和容错库旨在隔离对远程系统、服务和第三方库的访问点停止级联故障并在不可避免发生故障的复杂分布式系统中实现快速恢复。主要靠Spring的AOP实现 2. 实现原理 正常情况下断路器关闭服务消费者正常请求微服务一段时间内失败率达到一定阈值断路器将断开此时不在请求服务提供者而只是快速失败的方法断路方法断路器打开一段时间自动进入“半开”状态此时断路器可允许一个请求方法服务提供者如果请求调用成功则关闭断路器否则将保持断路器打开状态 断路器hystrix是保证了局部发生的错误不会错扩展到整个系统 从而保证系统 的即便出现局部问题也不会造成系统雪崩 二、相关功能
1. 请求缓存 概述 Hystirx为了降低访问服务的评率支持将一个q8ingqiu与返回接口做缓存处理。如果再次请求的URL没有变化nameHystrix不会请求服务而是直接从请求中将结果放回。这样可以大大降低访问服务的压力。 缺点 本地缓存集群模式下缓存无法同步不支持第三方缓存容器如Redis、MemCache 现在一般都是使用Redis集成方案 Redis的方式 1) 导入依赖 !-- spring boot data redis 依赖 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependency!-- commons-pool2 对象池依赖 1 --dependencygroupIdorg.apache.commons/groupIdartifactIdcommons-pool2/artifactId/dependency 2) 添加配置文件 # redis缓存redis:timeout: 10000 #设置连接超时时间host: 127.0.0.1port: 6379database: 0lettuce:pool:max-active: 8 # 最大连接数默认8max-wait: 10000 # 最大连接阻塞时间单位毫秒默认-1max-idle: 200 #最大空闲连接默认8min-idle: 5 #最小空闲连接默认 0 3) 增加Redis 配置 package cn.itmeteors.order.config;/*** Redis 配置类*/import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;Configuration
public class RedisConfig {// 重写 RedisTemplate 序列化Beanpublic RedisTemplateString, Object redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplateString, Object template new RedisTemplate();// 为 String 类型 key 设置序列化器template.setKeySerializer(new StringRedisSerializer());// 为 String 类型 value 设置序列化器template.setValueSerializer(new GenericJackson2JsonRedisSerializer());// 为 Hash 类型 key 设置序列化器template.setHashKeySerializer(new StringRedisSerializer());// 为 Hash 类型 value 设置序列化器template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}// 重写 Cache 序列化Beanpublic RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {RedisCacheWriter redisCacheWriter RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());RedisCacheConfiguration redisCacheConfiguration RedisCacheConfiguration.defaultCacheConfig()// 设置默认过期时间 30 min.entryTtl(Duration.ofMinutes(30))// 设置 key 和 value 的序列化.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));return new RedisCacheManager (redisCacheWriter, redisCacheConfiguration);}} 4增加缓存注解 5) 接口实现类增加缓存注解 Cacheable(cacheNames orderService:order:select)public Order selectOrderById(Long orderId) { // 调用list// 1.查询订单Order order orderMapper.findById(orderId);// 2.利用RestTemplate发起http请求查询用户// 2.1.url路径String url http://userservice/user/list;// 2.2.发送http请求实现远程调用ListUser userList restTemplate.getForObject(url, List.class);assert userList ! null;order.setUser(userList);return order;} 6结果 2. 请求合并实现 1). pom文件添加依赖 !-- spring-cloud netflix hystrix 依赖--dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-hystrix/artifactId/dependency 2). 在实现类进行请求合并 3开启熔断注解 EnableCaching
// 开启熔断器注解 2 选 1EnableHystrix 封装了 EnableCircuitBreaker
// EnableHystrix
EnableCircuitBreaker
EnableFeignClients(clients UserClient.class,defaultConfiguration DefaultFeignConfiguration.class)
public class OrderApplication { 4模拟同时发起多个请求 public Order queryOrderById(Long orderId) {// 1.查询订单Order order orderMapper.findById(orderId);// 2.利用RestTemplate发起http请求查询用户// 2.1.url路径String url http://userservice/user/1;String url2 http://userservice/user/2;String url3 http://userservice/user/3;String url4 http://userservice/user/4;String url5 http://userservice/user/5;// 2.2.发送http请求实现远程调用FutureUser user (FutureUser) restTemplate.getForObject(url, User.class);FutureUser user2 (FutureUser) restTemplate.getForObject(url2, User.class);FutureUser user3 (FutureUser) restTemplate.getForObject(url3, User.class);FutureUser user4 (FutureUser) restTemplate.getForObject(url4, User.class);FutureUser user5 (FutureUser) restTemplate.getForObject(url5, User.class);// 3.封装user到OrderListUser userList new ArrayList(1);try {userList.add(user.get());userList.add(user2.get());userList.add(user3.get());userList.add(user4.get());userList.add(user5.get());} catch (InterruptedException e) {throw new RuntimeException(e);} catch (ExecutionException e) {throw new RuntimeException(e);}order.setUser(userList);// 4.返回return order;} 3.线程池隔离 1介绍 对调用的接口进行隔离一个接口因为并发过高瘫痪时掉用的另一个接口不会瘫痪 2优点 使用线程池隔离可以安全「隔离依赖的服务」减少所依赖服务发生故障时的影响面。比如 A 服务发生异常导致请求大量超时对应的线程池被打满这时并不影响 C、D 服务的调用。 当失败的服务再次变得可用时线程池将清理并立即恢复而不需要一个长时间的恢复。 独立的线程池「提高了并发性」。 3缺点 请求在线程池中执行肯定会带来任务调度、排队和上下文切换带来的 CPU 开销。 因为涉及到跨线程那么就存在 ThreadLocal 数据的传递问题比如在主线程初始化的 ThreadLocal 变量在线程池线程中无法获取。 4代码示例 // 声明需要服务容错的方法// 线程池隔离HystrixCommand(groupKey order-userService-listPool,// 服务名称相同名称使用同一个线程池commandKey getList,// 接口名称默认为方法名threadPoolKey order-userService-listPool,// 线程池名称相同名称使用同一个线程池commandProperties {// 超时时间默认 1000msHystrixProperty(name execution.isolation.thread.timeoutInMilliseconds,value 5000)},threadPoolProperties {// 线程池大小HystrixProperty(name coreSize, value 6),// 队列等待阈值(最大队列长度默认 -1)HystrixProperty(name maxQueueSize, value 100),// 线程存活时间默认 1minHystrixProperty(name keepAliveTimeMinutes, value 2),// 超出队列等待阈值执行拒绝策略HystrixProperty(name queueSizeRejectionThreshold, value 100)}, fallbackMethod selectUserListFallback)public ListUser getList() {return userMapper.getAll();}// 托底数据private ListUser selectUserListFallback() {System.out.println(-----获得托底数据-----);return Arrays.asList(new User(1L, A, 地点1),new User(2L, B, 地点2),new User(3L, C, 地点3));}4. 信号量隔离 1介绍 每次调用线程当前请求通过计数信号量进行限制当信号量大于了最大请求数 maxConcurrentRequests 时进行限制调用 fallback 接口快速返回。信号量的调用是同步的也就是说每次调用都得阻塞调用方的线程直到结果返回。这样就导致了无法对访问做超时只能依靠调用协议超时无法主动释放 2代码示例 // 声明需要服务容错的方法// 信号量隔离HystrixCommand(commandProperties {// 超时时间默认 1000msHystrixProperty(name execution.isolation.thread.timeoutInMilliseconds,value 5000),// 信号量隔离HystrixProperty(name HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY,value SEMAPHORE),// 信号量最大并发调小一些方便模拟高并发HystrixProperty(name HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS,value 6)}, fallbackMethod selectUserListFallback)public ListUser getList() {return userMapper.getAll();}// 托底数据private ListUser selectUserListFallback() {System.out.println(-----获得托底数据-----);return Arrays.asList(new User(1L, A, 地点1),new User(2L, B, 地点2),new User(3L, C, 地点3));} 3) 线程池颗粒与信号隔离对比 隔离方式是否支持超时是否支持熔断隔离原理是否是异步调用资源消耗线程池隔离支持支持每个服务单独用线程池支持同步或异步大信号量隔离不支持支持通过信号量的计数器同步调用不支持异步小 5.服务熔断 1介绍 服务熔断是一种机制用于在出现服务故障、超时或异常情况时阻止请求继续发送到故障的服务上。当达到一定的失败阈值时熔断器会打开后续的请求将被快速失败而不再去调用故障的服务。当故障情况得到修复后熔断器会尝试关闭恢复对服务的正常调用。 2调用 在上面的代码执行fallbackMethod就会执行服务熔断 其他 除了上述功能Hystrix还有实时监控、指标收集、恢复等功能这里会留到后面的时候进行更新大家如果现在要学习的话可以从官网或其它地方得到相关的介绍和代码 参考文献 GitHub - Netflix/Hystrix: Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable. - GitHub - Netflix/Hystrix: Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.https://github.com/Netflix/Hystrix 最后
后续文章会陆续更新希望文章对你有所帮助..