欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringCloud之Hystrix的详细使用

程序员文章站 2022-03-04 12:29:21
目录***一.服务降级***2.不使用hystrix的项目3. 使用hystrix4. 全局的hystrix配置***二.服务熔断***1.熔断机制概述2.项目中使用1.概念服务降级:服务器繁忙,请稍...

1.概念

服务降级:服务器繁忙,请稍后再试,不让客户端等待,并立即返回一个友好的提示(一般发生在 程序异常,超时,服务熔断触发服务降级,线程池、信号量 打满也会导致服务降级)
服务熔断 : 达到最大服务访问后,直接拒绝访问,然后调用服务降级的方法并返回友好提示(如保险丝一样)
服务限流 : 秒杀等高并发操作,严禁一窝蜂的过来拥挤,排队进入,一秒钟n个,有序进行

***一.服务降级***

2.不使用hystrix的项目

大致的service和controller层如下

***************controller*****************
package com.sky.springcloud.controller;

import com.sky.springcloud.service.paymentservice;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.value;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.restcontroller;
import javax.annotation.resource;
@restcontroller
@slf4j
public class paymentcontroller {
    @resource
    private paymentservice paymentservice;
    @value("${server.port}")
    private string serverport;
    @getmapping("/payment/hystrix/ok/{id}")
    public string paymentinfo_ok(@pathvariable("id") integer id){
        string result = paymentservice.paymentinfo_ok(id);
        log.info("*****"+ result);
        return result;
    }
    @getmapping("/payment/hystrix/timeout/{id}")
    public string paymentinfo_timeout(@pathvariable("id") integer id){
        string result = paymentservice.payment_info_timeout(id);
}
*******************service******************** 
package com.sky.springcloud.service;
import org.springframework.stereotype.service;
import java.util.concurrent.timeunit;
@service
public class paymentserviceimpl implements paymentservice{
    @override
    public string paymentinfo_ok(integer id) {
        return "线程池:" + thread.currentthread().getname() + "paymentinfo_ok. id:" + id + "\t" + "~~~~~";
    public string payment_info_timeout(integer id) {
       try {
            timeunit.seconds.sleep(5);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        return "线程池:" + thread.currentthread().getname() + "paymentinfo_timeout. id:" + id + "\t" + "~~~~~";

在这种情况时,当通过浏览器访问 timeout这个方法,会三秒后返回结果,而当访问 ok 这个方法时,会直接返回结果(但是这是在访问量很少的时候,一旦访问量过多,访问ok时也会出现延迟,这里可以使用jmeter模拟两万个访问量,如下)

SpringCloud之Hystrix的详细使用

SpringCloud之Hystrix的详细使用

使用 jmeter 模拟后,再去访问ok,会明显出现加载的效果

3. 使用hystrix

在主启动类添加注解
@enablehystrix

package com.sky.springcloud;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cloud.netflix.eureka.enableeurekaclient;
import org.springframework.cloud.netflix.hystrix.enablehystrix;
@springbootapplication
@enableeurekaclient //启用eureka
@enablehystrix     //启用hystrix
public class payment8001 {
    public static void main(string[] args) {
        springapplication.run(payment8001.class,args);
    }
}

在原有的基础上,在service层加上如下注解

 @hystrixcommand(fallbackmethod = "payment_info_timeouthandler",//当服务降级时,调用payment_info_timeouthandler方法
                  commandproperties = {
            @hystrixproperty(name = "execution.isolation.thread.timeoutinmilliseconds",
            value = "3000")//设置时间为3秒,超过三秒就为时间超限
*****************改后的service*******************
package com.sky.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.hystrixcommand;
import com.netflix.hystrix.contrib.javanica.annotation.hystrixproperty;
import org.springframework.stereotype.service;

import java.util.concurrent.timeunit;
@service
public class paymentserviceimpl implements paymentservice{
    @override
    public string paymentinfo_ok(integer id) {
        return "线程池:" + thread.currentthread().getname() + "paymentinfo_ok. id:" + id + "\t" + "~~~~~";
    }

    @hystrixcommand(fallbackmethod = "payment_info_timeouthandler",commandproperties = {
            @hystrixproperty(name = "execution.isolation.thread.timeoutinmilliseconds",value = "3000")
    })
    public string payment_info_timeout(integer id) {
      try {
            timeunit.seconds.sleep(5);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
      // int a = 10 / 0;
        return "线程池:" + thread.currentthread().getname() + "paymentinfo_timeout. id:" + id + "\t" + "~~~~~";
    }
    public string payment_info_timeouthandler(integer id){
        return "线程超时或异常 " + thread.currentthread().getname();
    }
}

如上service所示,如果再次访问timeout需要等待五秒,但是hystrix设置的超时时间为三秒,所以当三秒后没有结果就会服务降级,从而调用timeouthandler这个指定 的方法来执行(或者有程序出错等情况也会服务降级)

4. 全局的hystrix配置

@defaultproperties(defaultfallback = “gloub_test”)

package com.sky.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.defaultproperties;
import com.netflix.hystrix.contrib.javanica.annotation.hystrixcommand;
import com.netflix.hystrix.contrib.javanica.annotation.hystrixproperty;
import org.springframework.stereotype.service;
@service
@defaultproperties(defaultfallback = "gloub_test")
public class paymentserviceimpl implements paymentservice{
    @override
    @hystrixcommand
    public string paymentinfo_ok(integer id) {
        int a = 10 / 0;
        return "线程池:" + thread.currentthread().getname() + "paymentinfo_ok. id:" + id + "\t" + "~~~~~";
    }
    @hystrixcommand(fallbackmethod = "payment_info_timeouthandler",commandproperties = {
            @hystrixproperty(name = "execution.isolation.thread.timeoutinmilliseconds",value = "3000")
    })
    public string payment_info_timeout(integer id) {
   /*     try {
            timeunit.seconds.sleep(5);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }*/
        return "线程池:" + thread.currentthread().getname() + "paymentinfo_timeout. id:" + id + "\t" + "~~~~~";
    public string payment_info_timeouthandler(integer id){
        return "线程超时或异常 " + thread.currentthread().getname();
    public string gloub_test(){
        return "走了全局的";
}

如上service所示,加了@hystrixcommand的方法里,
如果没指定fallbackmethod 就会默认去找全局的defaultfallback
这里 当paymentinfo_ok 方法出错时,会调用gloub_test方法
当payment_info_timeout出错时,会调用payment_info_timeouthandler方法

 ***二.服务熔断***

1.熔断机制概述

熔断机制是应对雪崩效应的一种微服务链路保护机制,当扇出链路的某个微服务出错不可用或者响应时间太长,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的相应信息.当检测到该节点微服务调用相应正常后,恢复调用链路.

2.项目中使用

在上面的基础上,改写service和controller(添加以下代码)

//是否开启服务熔断(断路器)
 @hystrixproperty(name = "circuitbreaker.enabled",value = "true"),
 //服务请求的次数 
 @hystrixproperty(name = "circuitbreaker.requestvolumethreshold",value = "10"),
 //时间的窗口期
 @hystrixproperty(name = "circuitbreaker.sleepwindowinmilliseconds", value = "10000"),
 //当失败率达到多少后发生熔断
 @hystrixproperty(name = "circuitbreaker.errorthresholdpercentage",value = "60"), 

******************service*****************
    @hystrixcommand(fallbackmethod = "paymentcircuitbreaker_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 paymentcircuitbreaker(@pathvariable("id") integer id){
        if(id<0){
            throw new runtimeexception("********** id不能为负");
        }
        string serialnumber = idutil.simpleuuid();
        return thread.currentthread().getname() + "\t" + serialnumber;
    }
    public string paymentcircuitbreaker_fallback(@pathvariable("id") integer id){
        return  "id 不能为负:" + id;
************controller********************
    @getmapping("/payment/circuit/{id}")
        string result = paymentservice.paymentcircuitbreaker(id);
        log.info(result + "***********");
        return result;

如上所示,当访问paymentcircuitbreaker时,如果id小于零则会有一个运行错误,这时候就会通过服务降级来调用paymentcircuitbreaker_fallback方法,当错误的次数达到60%的时候(自己设的),就会出现服务熔断,这个时候再访问id大于零的情况,也会发生服务降级,因为开起了服务熔断,需要慢慢的恢复正常.

到此这篇关于springcloud之hystrix的详细使用的文章就介绍到这了,更多相关springcloud hystrix使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!