给出Java编写熔断和限流的代码
时间: 2023-03-30 22:04:19 浏览: 98
Sentinel限流简单示例Java代码.zip
以下是Java编写熔断和限流的示例代码:
熔断:
```
public class CircuitBreaker {
private int failureThreshold;
private int resetTimeout;
private long lastFailureTime;
private int failureCount;
public CircuitBreaker(int failureThreshold, int resetTimeout) {
this.failureThreshold = failureThreshold;
this.resetTimeout = resetTimeout;
this.lastFailureTime = ;
this.failureCount = ;
}
public boolean allowRequest() {
if (failureCount >= failureThreshold) {
long now = System.currentTimeMillis();
if (now - lastFailureTime >= resetTimeout) {
failureCount = ;
} else {
return false;
}
}
return true;
}
public void markSuccess() {
failureCount = ;
}
public void markFailure() {
failureCount++;
lastFailureTime = System.currentTimeMillis();
}
}
```
限流:
```
public class RateLimiter {
private int maxRequests;
private int requestCount;
private long intervalStart;
public RateLimiter(int maxRequests) {
this.maxRequests = maxRequests;
this.requestCount = ;
this.intervalStart = System.currentTimeMillis();
}
public synchronized boolean allowRequest() {
long now = System.currentTimeMillis();
if (now - intervalStart >= 100) {
requestCount = ;
intervalStart = now;
}
if (requestCount >= maxRequests) {
return false;
}
requestCount++;
return true;
}
}
```
阅读全文