Hystrix (容错,回退,降级,缓存)

Stella981
• 阅读 561

Hystrix熔断机制就像家里的保险丝一样,若同时使用高功率的电器,就会烧坏电路,这时候保险丝自动断开就有效的保护了电路。而我们程序中也同样是这样。例如若此时数据库压力太大速度很慢,此时还有不断的请求访问后台,就会造成数据库崩溃。这时候hystrix容错机制,可以为客户端请求设置超时链接,添加回退的逻辑,减少集群压力。

Hystrix  (容错,回退,降级,缓存)

1.1 导依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version> 
        <relativePath/>
    </parent>
    <!-- springCloud -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- eureka客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <!-- hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

1.2 配置application.yml

# 指定端口
server:
  port: 8085
  context-path: /demo
# 服务名称
spring:
  application:
    name: hystrix

# eureka服务器地址
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

1.3 配置Hystrix过滤器

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
/**
 * urlPatterns:拦截所有路径(拦截规则)
 * filterName:过滤器名称
 */
@WebFilter(urlPatterns = "/*", filterName = "hystrixFilter")
public class HystrixFilterConf implements Filter{
    public void destroy() { }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 初始化Hystrix上下文
        HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            
        } finally {
            ctx.shutdown();
        }
    }
    public void init(FilterConfig arg0) throws ServletException { }
}

1.4 主函数入口

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient  //开启Eureka
@EnableCircuitBreaker//开启断路器
@ServletComponentScan//扫描servlet过滤器监听器
public class ServerMain {

    public static void main(String[] args) {
        new SpringApplicationBuilder(ServerMain.class).web(true).run(args);
    }
}

二: hystrix 的 熔断,降级 机制。

2.1 回退机制案例

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * Hystrix回退机制(熔断,降级)
 */
@Service
public class RollbackService {

    /**
     * fallbackMethod: 指定回退方法
     * 
     * coreSize: 线程池最大数量
     * maxQueueSize: 线程池最大队列,默认-1通过SynchronousQueue来实现; 否则使用LinkedBlockingQueue实现
     * queueSizeRejectionThreshold: 当maxQueueSize是LinkedBlockingQueue时,即使没有达到最大列队也会据绝请求。
     * 
     * timeoutInMilliseconds: 超时时间
     * requestVolumeThreshold: 单位时间内超过这个多个请求失败才执行熔断
     */
    @RequestMapping(value = "/testRollback")
    @HystrixCommand(fallbackMethod = "myRollback", 
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "30"), 
            @HystrixProperty(name = "maxQueueSize", value = "-1"),
            @HystrixProperty(name = "queueSizeRejectionThreshold", value = "-1")
        }, 
        commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "1")
        })
    public String testRollback() {
        try {// 模拟请求阻塞
            Thread.sleep(4000);
        } catch (Exception e) {
        }
        return "恭喜你访问成功!";
    }
    /** 回退方法  */
    public String myRollback() {
        return "服务器压力过大,明年再来吧!";
    }
}

2.2 编写接口, 调用测试。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RollbackController {

    @Autowired
    private RollbackService rollbackService;
    
    @RequestMapping("/testRollback")
    public String testRollback() {
        return rollbackService.testRollback();
    }
}

Hystrix  (容错,回退,降级,缓存)

三: hystrix 缓存机制:hystrix的缓存有点像mybatis默认开启的一级缓存:在session关闭之前(一次会话期间),使用同样的参数调用同一个方法,实际只查询一次。

3.1 缓存逻辑

import org.springframework.stereotype.Service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
@Service
public class CacheService {

    @CacheResult
    @HystrixCommand
    public void cacheMember(Integer id) {
        System.out.println("调用 cacheMember 方法");
    }
    
    /**
     * commandKey:缓存的key
     *       获取和删除必须用同一个key,并必须是同一次请求。
     */
    @CacheResult
    @HystrixCommand(commandKey = "myCacheKey")
    public void getCache(Integer id) {
        System.out.println("执行查询方法");
    }
    @CacheRemove(commandKey = "myCacheKey")
    @HystrixCommand
    public void removeCache(Integer id) {
        System.out.println("删除缓存方法");
    }
}

3.2 缓存接口开发

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CacheController {
    
    @Autowired
    private CacheService cacheService;

    @RequestMapping(value = "/cache", method = RequestMethod.GET, 
            produces = MediaType.APPLICATION_JSON_VALUE)
    public String cache() {
        for(int i = 0; i < 3; i++) {
            /** 在同一次请求里面调用了3次同一方法,会发现,控制台只
             *  输出了一次,说明后2次走的缓存没调方法的逻辑    */
            cacheService.cacheMember(1);
        }
        System.out.println("测试完毕");
        return "";
    }
    @RequestMapping(value = "/rc", method = RequestMethod.GET, 
            produces = MediaType.APPLICATION_JSON_VALUE)
    public String testRemoveCache() {
        cacheService.getCache(1);
        cacheService.getCache(1);
        
        cacheService.removeCache(1);
        System.out.println("#########  分隔线   ###########");
        cacheService.getCache(1);
        System.out.println("测试完毕");
        return "";
    }
}

Hystrix  (容错,回退,降级,缓存)

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
待兔 待兔
2个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Souleigh ✨ Souleigh ✨
3年前
前端性能优化 - 雅虎军规
无论是在工作中,还是在面试中,web前端性能的优化都是很重要的,那么我们进行优化需要从哪些方面入手呢?可以遵循雅虎的前端优化35条军规,这样对于优化有一个比较清晰的方向.35条军规1.尽量减少HTTP请求个数——须权衡2.使用CDN(内容分发网络)3.为文件头指定Expires或CacheControl,使内容具有缓存性。4.避免空的
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
SpringCloud-Hystrix服务熔断与降级工作原理&源码 | 京东物流技术团队
在生活中,如果电路的负载过高,保险箱会自动跳闸,以保护家里的各种电器,这就是熔断器的一个活生生例子。在Hystrix中也存在这样一个熔断器,当所依赖的服务不稳定时,能够自动熔断,并提供有损服务,保护服务的稳定性。在运行过程中,Hystrix会根据接口的执行状态(成功、失败、超时和拒绝),收集并统计这些数据,根据这些信息来实时决策是否进行熔断。
Python进阶者 Python进阶者
8个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这