Spring Cloud Circuit Breaker


断路器是用来在程序中避免多层雪崩效应,能够提高程序的性能。

导入hystrix依赖

新建springboot项目,在pom文件中引入依赖。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Greenwich.SR2</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencies>

初识hystrix

Spring Cloud通过hystrix来实现Circuit Breaker,通过在Service层的方法前加入注释@HystrixCommand来触发机制,触发的条件是在一定时间(属性名metrics.rollingStats.timeInMilliseconds,默认10秒)调用超过一定次数(属性名circuitBreaker.requestVolumeThreshold,默认20次)并且失败次数达到一定概率(属性名circuitBreaker.errorThresholdPercentage ,默认50%)。而失败一般是由异常或者方法超时(默认1s)触发。

TestController.java

package com.example.hystrix.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TestService {
   
    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public void test1(int input){
   
        System.out.println("test1 input:"+input);
        System.out.println("test1 output:"+1/input);
    }

    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public void test2(int input) throws InterruptedException {
   
        TimeUnit.MILLISECONDS.sleep(1500);
        System.out.println("test2 "+input);
    }

    public void fallbackMethod(int input){
   
        System.out.println("execute fail, the input is "+input);
    }
}

fallbackMethod为熔断触发的函数。test1通过传入0来触发异常,test2通过超时触发异常。

HystrixApplication.java

一定要加EnableCircuitBreaker注释

package com.example.hystrix;

import com.example.hystrix.service.TestService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
@EnableCircuitBreaker
public class HystrixApplication {
   
    public static void main(String[] args) throws InterruptedException {
   
        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(HystrixApplication.class, args);
        TestService testService = configurableApplicationContext.getBean(TestService.class);
        //1
        testService.test1(1);
        //3
        testService.test1(0);
        //2
        testService
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值