Skip to content

Commit

Permalink
Update demo for circuit breaking (DegradeRule)
Browse files Browse the repository at this point in the history
Signed-off-by: Eric Zhao <sczyh16@gmail.com>
  • Loading branch information
sczyh30 committed Jul 30, 2020
1 parent 07b8111 commit 19db20f
Show file tree
Hide file tree
Showing 3 changed files with 155 additions and 321 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -19,127 +19,131 @@
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreaker.State;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.EventObserverRegistry;
import com.alibaba.csp.sentinel.util.TimeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
* <p>
* Degrade is used when the resources are in an unstable state, these resources
* will be degraded within the next defined time window. There are three ways to
* measure whether a resource is stable or not:
* <ul>
* <li>
* Exception ratio: When the ratio of exception count per second and the success
* qps greats than or equals to the threshold, access to the resource will be blocked
* in the coming time window.
* </li>
* <li>
* Exception Count, see {@link ExceptionCountDegradeDemo}.
* </li>
* <li>
* For average response time, see {@link RtDegradeDemo}.
* </li>
* </ul>
* </p>
*
* @author jialiang.linjl
* @author Eric Zhao
*/
public class ExceptionRatioDegradeDemo {
public class ExceptionRatioCircuitBreakerDemo {

private static final String KEY = "abc";
private static final String KEY = "some_service";

private static AtomicInteger total = new AtomicInteger();
private static AtomicInteger pass = new AtomicInteger();
private static AtomicInteger block = new AtomicInteger();
private static AtomicInteger bizException = new AtomicInteger();

private static volatile boolean stop = false;
private static final int threadCount = 1;
private static int seconds = 60 + 40;
private static int seconds = 120;

public static void main(String[] args) throws Exception {
tick();
initDegradeRule();

for (int i = 0; i < threadCount; i++) {
Thread entryThread = new Thread(new Runnable() {

@Override
public void run() {
int count = 0;
while (true) {
count++;
Entry entry = null;
try {
Thread.sleep(20);
entry = SphU.entry(KEY);
// token acquired, means pass
pass.addAndGet(1);
if (count % 2 == 0) {
// biz code raise an exception.
throw new RuntimeException("throw runtime ");
}
} catch (BlockException e) {
block.addAndGet(1);
} catch (Throwable t) {
bizException.incrementAndGet();
Tracer.trace(t);
} finally {
total.addAndGet(1);
if (entry != null) {
entry.exit();
}
registerStateChangeObserver();
startTick();

final int concurrency = 8;
for (int i = 0; i < concurrency; i++) {
Thread entryThread = new Thread(() -> {
while (true) {
Entry entry = null;
try {
entry = SphU.entry(KEY);
sleep(ThreadLocalRandom.current().nextInt(5, 10));
pass.addAndGet(1);

// Error probability is 45%
if (ThreadLocalRandom.current().nextInt(0, 100) > 55) {
// biz code raise an exception.
throw new RuntimeException("oops");
}
} catch (BlockException e) {
block.addAndGet(1);
sleep(ThreadLocalRandom.current().nextInt(5, 10));
} catch (Throwable t) {
bizException.incrementAndGet();
// It's required to record exception here manually.
Tracer.traceEntry(t, entry);
} finally {
total.addAndGet(1);
if (entry != null) {
entry.exit();
}
}
}

});
entryThread.setName("working-thread");
entryThread.setName("sentinel-simulate-traffic-task-" + i);
entryThread.start();
}
}

private static void registerStateChangeObserver() {
EventObserverRegistry.getInstance().addStateChangeObserver("logging",
(prevState, newState, rule, snapshotValue) -> {
if (newState == State.OPEN) {
System.err.println(String.format("%s -> OPEN at %d, snapshotValue=%.2f", prevState.name(),
TimeUtil.currentTimeMillis(), snapshotValue));
} else {
System.err.println(String.format("%s -> %s at %d", prevState.name(), newState.name(),
TimeUtil.currentTimeMillis()));
}
});
}

private static void initDegradeRule() {
List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule();
rule.setResource(KEY);
// set limit exception ratio to 0.1
rule.setCount(0.1);
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
rule.setTimeWindow(10);
rule.setMinRequestAmount(20);
List<DegradeRule> rules = new ArrayList<>();
DegradeRule rule = new DegradeRule(KEY)
.setGrade(CircuitBreakerStrategy.ERROR_RATIO.getType())
// Set ratio threshold to 50%.
.setCount(0.5d)
.setStatIntervalMs(30000)
.setMinRequestAmount(50)
// Retry timeout (in second)
.setTimeWindow(10);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
System.out.println("Degrade rule loaded: " + rules);
}

private static void tick() {
private static void sleep(int timeMs) {
try {
TimeUnit.MILLISECONDS.sleep(timeMs);
} catch (InterruptedException e) {
// ignore
}
}

private static void startTick() {
Thread timer = new Thread(new TimerTask());
timer.setName("sentinel-timer-task");
timer.setName("sentinel-timer-tick-task");
timer.start();
}

static class TimerTask implements Runnable {
@Override
public void run() {
long start = System.currentTimeMillis();
System.out.println("begin to statistic!!!");
System.out.println("Begin to run! Go go go!");
System.out.println("See corresponding metrics.log for accurate statistic data");

long oldTotal = 0;
long oldPass = 0;
long oldBlock = 0;
long oldBizException = 0;
while (!stop) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
sleep(1000);

long globalTotal = total.get();
long oneSecondTotal = globalTotal - oldTotal;
oldTotal = globalTotal;
Expand All @@ -166,7 +170,7 @@ public void run() {
}
long cost = System.currentTimeMillis() - start;
System.out.println("time cost: " + cost + " ms");
System.out.println("total:" + total.get() + ", pass:" + pass.get()
System.out.println("total: " + total.get() + ", pass:" + pass.get()
+ ", block:" + block.get() + ", bizException:" + bizException.get());
System.exit(0);
}
Expand Down
Loading

0 comments on commit 19db20f

Please sign in to comment.