技术方案
- 服务熔断:可以使用Hystrix或Sentinel等框架。以Hystrix为例,它会监控服务调用的失败率、超时等指标。当失败率超过一定阈值(如50%),且在一定时间窗口(如10秒)内请求数达到一定数量(如20个),就会触发熔断,后续请求不再调用实际的商品详情服务,而是直接返回fallback内容。
- 服务降级:同样可借助Hystrix或Sentinel。在高并发场景下,主动降低服务的某些非核心功能或质量,优先保障核心功能可用。比如简化商品详情展示,只返回关键信息,如商品名称、价格等,而不返回复杂的描述、图片等信息。
关键代码逻辑(以Spring Cloud Alibaba Sentinel为例)
- 引入依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
- 配置Sentinel规则:
可以通过Sentinel控制台动态配置规则,也可在代码中配置。
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
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 java.util.ArrayList;
import java.util.List;
public class SentinelConfig {
public static void initDegradeRule() {
List<DegradeRule> rules = new ArrayList<>();
DegradeRule rule = new DegradeRule();
rule.setResource("productDetailService"); // 资源名,对应商品详情服务
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO); // 基于异常比例熔断
rule.setCount(0.5); // 异常比例阈值,50%
rule.setTimeWindow(10); // 熔断时间窗口,10秒
rule.setMinRequestAmount(20); // 最小请求数,20个
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}
}
- 实现降级逻辑:
public class ProductDetailService {
public String getProductDetail(String productId) {
Entry entry = null;
try {
entry = SphU.entry("productDetailService");
// 实际调用商品详情服务的代码
return realGetProductDetail(productId);
} catch (BlockException e) {
// 服务降级逻辑
return "Product detail service is degraded, only show basic info.";
} finally {
if (entry != null) {
entry.exit();
}
}
}
private String realGetProductDetail(String productId) {
// 实际查询商品详情逻辑
return "Full product detail for product " + productId;
}
}
相关参数的设置依据
- 异常比例阈值(如50%):这个值不能设置过低,否则服务可能因为偶尔的波动就熔断;也不能过高,不然高并发下大量请求失败也不会触发熔断。50%是一个比较适中的经验值,可根据实际业务场景和历史数据调整。
- 熔断时间窗口(如10秒):时间窗口过短,服务可能频繁熔断和恢复,影响用户体验;过长则在服务恢复正常后,还长时间处于熔断状态。10秒能给服务一个相对合理的恢复时间,期间用户得到降级的响应。
- 最小请求数(如20个):设置最小请求数是为了避免因少量请求失败就触发熔断。如果请求数过少,失败可能是偶然因素导致,设置该值可使熔断判断更准确。