1:断路器只有两种状态,开启和关闭,默认不开启
2:通过两个变量保存总请求数和异常请求书-->线程安全
3:给定一个最大异常的阈值-->到达最大开启断路器
4:给定一个异常比例阈值-->
-->当请求数大于0 且 异常请求数大于0
-->异常/总请求>异常比例
-->到达开启断路器
5:定义两个自增计数器保存请求和异常请求
6:给定一个充值方法,可以通过异步线程重置
- package com.trpc.protection;
-
- import java.util.Random;
- import java.util.concurrent.atomic.AtomicInteger;
-
- /**
- * 断路器
- */
- public class CircuitBreaker {
-
- //默认不开启
- private volatile boolean isOpen=false;
-
- //总请求
- private AtomicInteger requestCount=new AtomicInteger(0);
-
- //异常请求
- private AtomicInteger errorRequest=new AtomicInteger(0);
-
- //异常阈值
- private int maxErrorRequest;
- private float MaxErrorRate;
-
- public CircuitBreaker(int maxErrorRequest, float maxErrorRate) {
- this.maxErrorRequest = maxErrorRequest;
- this.MaxErrorRate = maxErrorRate;
- }
-
- /**
- * 判断是否开启
- */
- public synchronized boolean isBreak(){
- //1 断路器打开状态
- if (isOpen){
- return true;
- }
- //2 异常超过最大数
- if (errorRequest.get() > maxErrorRequest){
- this.isOpen=true;
- return true;
- }
-
- //3 存在正确请求和异常请求 同时:大于异常比例
- if (errorRequest.get() > 0 && errorRequest.get() > 0 &&
- errorRequest.get()/(float)requestCount.get() >MaxErrorRate
- ){
- this.isOpen=true;
- return true;
- }
- return false;
- }
-
- //记录请求数
- public void recordRequest(){
- this.requestCount.getAndIncrement(); //自增
- }
-
- //记录异常请求数
- public void recordErrorRequest(){
- this.errorRequest.getAndIncrement(); //自增
- }
-
- /**
- * 重置
- */
- public void reset(){
- this.isOpen=false;
- this.requestCount.set(0);
- this.errorRequest.set(0);
- }
- }
测试方法
- public static void main(String[] args) {
- //
- // CircuitBreaker circuitBreaker = new CircuitBreaker(3,0.5F);
- // //熔断比例超过1.1F出现三个异常
- // new Thread(() ->{
- // for (int i = 0; i < 1000; i++) {
- //
- // try {
- // Thread.sleep(100);
- // } catch (InterruptedException e) {
- // throw new RuntimeException(e);
- // }
- // //添加总请求数
- // circuitBreaker.recordRequest();
- // int num = new Random().nextInt(100);
- // if(num > 70){
- // //添加异常请求
- // circuitBreaker.recordErrorRequest();
- // }
- //
- // boolean aBreak = circuitBreaker.isBreak();
- //
- // String result = aBreak ? "断路器阻塞了请求":"断路器放行了请求";
- //
- // System.out.println(result);
- //
- // }
- // }).start();
- //
- // //每隔两秒钟重置熔断器
- // new Thread(() -> {
- // for (;;) {
- // try {
- // Thread.sleep(2000);
- // } catch (InterruptedException e) {
- // throw new RuntimeException(e);
- // }
- // System.out.println("-----------------------------------------");
- // circuitBreaker.reset();
- // }
- // }).start();
- //
- // try {
- // Thread.sleep(1000000);
- // } catch (InterruptedException e) {
- // throw new RuntimeException(e);
- // }
- //
- }