本文目录导读:

我来提供一个完整的Java降级(Degradation)案例,包含多种降级策略的实现。
基础版本 - 简单降级
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 基础降级示例
*/
public class BasicDegradationExample {
// 模拟外部服务
static class ExternalService {
private final AtomicInteger failureCount = new AtomicInteger(0);
private final AtomicInteger successCount = new AtomicInteger(0);
// 模拟不稳定服务
public String call() {
// 模拟60%的概率调用失败
if (Math.random() < 0.6) {
failureCount.incrementAndGet();
throw new RuntimeException("External service failed");
}
successCount.incrementAndGet();
return "Success response from external service";
}
}
// 本地降级服务
static class LocalFallbackService {
public String getFallbackData() {
return "Local fallback data - degradation active";
}
}
// 降级管理器
static class DegradationManager {
private static final int MAX_FAILURE_COUNT = 5;
private final AtomicInteger failureCount = new AtomicInteger(0);
private volatile boolean degraded = false;
// 降级控制方法
public boolean isDegraded() {
return degraded;
}
public void recordFailure() {
int count = failureCount.incrementAndGet();
if (count >= MAX_FAILURE_COUNT) {
degraded = true;
System.out.println("⚠️ 触发降级!连续失败" + count + "次");
}
}
public void recordSuccess() {
failureCount.set(0);
if (degraded) {
System.out.println("✅ 服务恢复,解除降级");
}
degraded = false;
}
public void reset() {
failureCount.set(0);
degraded = false;
}
}
public static void main(String[] args) {
ExternalService externalService = new ExternalService();
LocalFallbackService fallbackService = new LocalFallbackService();
DegradationManager degradationManager = new DegradationManager();
// 主调用逻辑
for (int i = 0; i < 20; i++) {
try {
// 检查是否处于降级状态
if (degradationManager.isDegraded()) {
System.out.println("第" + (i+1) + "次调用: [降级] " +
fallbackService.getFallbackData());
continue;
}
// 调用外部服务
String result = externalService.call();
degradationManager.recordSuccess();
System.out.println("第" + (i+1) + "次调用: [正常] " + result);
} catch (Exception e) {
degradationManager.recordFailure();
System.out.println("第" + (i+1) + "次调用: [降级] 错误: " + e.getMessage()
+ " -> 使用本地降级数据");
}
// 模拟时间间隔
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
高级版本 - 基于注解和Spring
import java.lang.annotation.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 高级降级框架
*/
public class AdvancedDegradationExample {
// 1. 降级注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Degrade {
int failureThreshold() default 3; // 失败阈值
long timeout() default 1000; // 超时时间(ms)
String fallbackMethod() default ""; // 降级方法名
}
// 2. 降级配置
static class DegradationConfig {
private int failureThreshold;
private long timeout;
private String fallbackMethod;
public DegradationConfig(Degrade degrade) {
this.failureThreshold = degrade.failureThreshold();
this.timeout = degrade.timeout();
this.fallbackMethod = degrade.fallbackMethod();
}
}
// 3. 服务接口
interface OrderService {
@Degrade(failureThreshold = 3, timeout = 2000, fallbackMethod = "getDefaultOrders")
String getOrderInfo(String orderId);
String getDefaultOrders(String orderId);
}
// 4. 真实服务实现
static class RealOrderService implements OrderService {
@Override
public String getOrderInfo(String orderId) {
// 模拟不稳定服务,延迟或失败
try {
if (Math.random() < 0.5) {
throw new RuntimeException("Order service unavailable");
}
Thread.sleep(100); // 模拟处理时间
return "Real order info for " + orderId;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
@Override
public String getDefaultOrders(String orderId) {
return "Default order info for " + orderId + " [降级数据]";
}
}
// 5. 降级代理类
static class DegradationProxy implements InvocationHandler {
private Object target;
private ExecutorService executor;
// 每个方法的降级状态
private ConcurrentHashMap<Method, DegradationState> states = new ConcurrentHashMap<>();
static class DegradationState {
AtomicInteger failureCount = new AtomicInteger(0);
volatile boolean degraded = false;
volatile long degradationStartTime = 0;
}
public DegradationProxy(Object target) {
this.target = target;
this.executor = Executors.newFixedThreadPool(10);
}
public static Object wrap(Object target) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new DegradationProxy(target)
);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// 获取方法上的降级注解
Degrade degrade = method.getAnnotation(Degrade.class);
if (degrade == null) {
// 无降级注解,直接调用
return method.invoke(target, args);
}
DegradationConfig config = new DegradationConfig(degrade);
DegradationState state = states.computeIfAbsent(method, k -> new DegradationState());
// 检查是否降级
if (isDegraded(state, method)) {
return executeFallback(method, args, config);
}
// 异步执行,支持超时
Future<Object> future = executor.submit(() -> {
try {
return method.invoke(target, args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
});
try {
// 带超时获取结果
Object result = future.get(config.timeout, TimeUnit.MILLISECONDS);
// 成功,重置失败计数
state.failureCount.set(0);
return result;
} catch (TimeoutException e) {
// 超时,记录失败
recordFailure(state, method);
return executeFallback(method, args, config);
} catch (Exception e) {
// 调用失败,记录失败
recordFailure(state, method);
return executeFallback(method, args, config);
}
}
private boolean isDegraded(DegradationState state, Method method) {
if (state.degraded) {
// 自动恢复机制:降级一段时间后尝试恢复
long degradationDuration = System.currentTimeMillis() - state.degradationStartTime;
if (degradationDuration > 10000) { // 10秒后尝试恢复
state.degraded = false;
state.failureCount.set(0);
System.out.println("[恢复] 方法 " + method.getName() + " 尝试恢复正常");
return false;
}
return true;
}
return false;
}
private void recordFailure(DegradationState state, Method method) {
int count = state.failureCount.incrementAndGet();
if (count >= 3) { // 降级阈值
state.degraded = true;
state.degradationStartTime = System.currentTimeMillis();
System.out.println("[降级] 方法 " + method.getName() + " 连续失败" + count + "次");
}
}
private Object executeFallback(Method method, Object[] args, DegradationConfig config) {
System.out.println("[降级执行] 方法: " + method.getName() + " 使用降级逻辑");
// 方法降级
if (!config.fallbackMethod.isEmpty()) {
try {
Method fallbackMethod = target.getClass()
.getMethod(config.fallbackMethod,
getParameterTypes(args));
return fallbackMethod.invoke(target, args);
} catch (Exception e) {
// 降级方法失败,返回默认值
System.out.println("降级方法执行失败: " + e.getMessage());
}
}
// 默认降级值
return "null";
}
private Class<?>[] getParameterTypes(Object[] args) {
if (args == null) return new Class<?>[0];
Class<?>[] types = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
types[i] = args[i].getClass();
}
return types;
}
}
// 6. 测试主类
public static void main(String[] args) throws InterruptedException {
// 创建代理对象
OrderService orderService = (OrderService) DegradationProxy.wrap(new RealOrderService());
// 模拟调用
for (int i = 0; i < 10; i++) {
System.out.println("=== 第" + (i+1) + "次调用 ===");
Object result = orderService.getOrderInfo("ORDER_001");
System.out.println("结果: " + result);
System.out.println();
Thread.sleep(1000);
}
// 关闭执行器
((DegradationProxy) Proxy.getInvocationHandler(orderService)).executor.shutdown();
}
}
基于Hystrix风格的降级实现
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Hystrix风格降级实现
*/
public class HystrixStyleDegradation {
// 降级命令
interface Command<T> {
T execute(); // 真实执行
T fallback(); // 降级执行
}
// 降级状态
static class CircuitBreaker {
private final int failureThreshold; // 失败阈值
private final long timeout; // 熔断超时时间
private final AtomicInteger failureCount = new AtomicInteger(0);
private volatile boolean open = false; // 熔断开关
private volatile long lastFailureTime = 0;
public CircuitBreaker(int failureThreshold, long timeout) {
this.failureThreshold = failureThreshold;
this.timeout = timeout;
}
// 是否允许执行
public boolean isAllowed() {
if (open) {
// 如果在超时时间内,不允许
if (System.currentTimeMillis() - lastFailureTime < timeout) {
return false;
}
// 超时后允许半开放状态
open = false;
failureCount.set(0);
return true;
}
return true;
}
public void recordSuccess() {
if (open) {
System.out.println("✅ 熔断器关闭,服务恢复");
}
failureCount.set(0);
open = false;
}
public void recordFailure() {
int count = failureCount.incrementAndGet();
if (count >= failureThreshold) {
open = true;
lastFailureTime = System.currentTimeMillis();
System.out.println("🔥 熔断器打开!连续失败" + count + "次");
}
}
public boolean isOpen() {
return open;
}
}
// 降级执行器
static class CommandExecutor {
private final Map<String, CircuitBreaker> breakers = new ConcurrentHashMap<>();
public <T> T execute(String commandName, Command<T> command) {
CircuitBreaker breaker = breakers.computeIfAbsent(
commandName, k -> new CircuitBreaker(3, 5000));
// 检查熔断状态
if (!breaker.isAllowed()) {
System.out.println("[熔断] " + commandName + " 处于熔断状态,执行降级");
return command.fallback();
}
try {
T result = command.execute();
breaker.recordSuccess();
return result;
} catch (Exception e) {
breaker.recordFailure();
System.out.println("[失败] " + commandName + " 执行失败: " + e.getMessage());
return command.fallback();
}
}
}
public static void main(String[] args) throws InterruptedException {
CommandExecutor executor = new CommandExecutor();
// 创建命令
Command<String> getUserCommand = new Command<String>() {
@Override
public String execute() {
// 模拟失败的服务
if (Math.random() < 0.7) {
throw new RuntimeException("User service unavailable");
}
return "User data from remote service";
}
@Override
public String fallback() {
return "User data from local cache [降级]";
}
};
// 执行20次调用
for (int i = 1; i <= 20; i++) {
if (i == 15) {
System.out.println("\n=== 模拟服务恢复 ===");
getUserCommand = new Command<String>() {
@Override
public String execute() {
return "User data from remote service (recovered)";
}
@Override
public String fallback() {
return "Fallback data";
}
};
}
String result = executor.execute("getUser", getUserCommand);
System.out.println("第" + i + "次: " + result);
Thread.sleep(500);
}
}
}
使用示例
public class DegradationDemo {
public static void main(String[] args) {
// 1. 基础降级
System.out.println("=== 基础降级示例 ===");
BasicDegradationExample.main(args);
// 2. 高级降级
System.out.println("\n=== 高级降级示例 ===");
AdvancedDegradationExample.main(args);
// 3. Hystrix风格降级
System.out.println("\n=== Hystrix风格降级示例 ===");
HystrixStyleDegradation.main(args);
}
}
核心知识点
-
降级策略:
- 静态降级:预先配置
- 动态降级:根据状态自动触发
-
降级级别:
- 超时降级
- 失败次数降级
- 并发降级
- 依赖服务降级
-
降级方式:
- 返回默认值
- 使用缓存数据
- 调用备用服务
- 排队等待
-
熔断器模式:
- 关闭:正常调用
- 打开:快速失败
- 半开:尝试恢复
这个案例提供了从简单到复杂的完整降级实现,可以根据具体需求选择合适的方案。