新聞中心
本文將介紹如何使用Redis實(shí)現(xiàn)熔斷和限流兩個重要的微服務(wù)治理特性,以提高系統(tǒng)的穩(wěn)定性和可靠性。微服務(wù)架構(gòu)中的每個服務(wù)都有可能發(fā)生宕機(jī)、超時(shí)等問題,如果不對其進(jìn)行一定的處理,可能會引發(fā)級聯(lián)宕機(jī)問題。而進(jìn)行熔斷和限流可以在一定程度上避免此類問題的發(fā)生,同時(shí)也能提高整體系統(tǒng)的性能和可用性。

沙洋ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)建站的ssl證書銷售渠道,可以享受市場價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!
基于Redis的熔斷
熔斷是指當(dāng)服務(wù)調(diào)用失敗率或錯誤率達(dá)到一定閾值時(shí),系統(tǒng)將自動停止調(diào)用該服務(wù)一段時(shí)間,以免進(jìn)一步引發(fā)級聯(lián)失敗?;赗edis的熔斷通常是通過記錄服務(wù)的調(diào)用成功和失敗次數(shù),并且根據(jù)指定的失敗閾值進(jìn)行自動熔斷和恢復(fù)。Redis提供了一個非常方便的atomic操作–“INCR”,可用于計(jì)數(shù)。
在spring-cloud中集成hystrix和redis的實(shí)現(xiàn)如下:
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
PUBLIC class HystrixRedisAutoConfiguration {
@Autowired(required = false)
private List instanceFactories = Collections.emptyList();
@Autowired
private RedisCacheHelper redisCache;
@PostConstruct
public void init() {
HystrixPlugins.getInstance().registerCommandExecutionHook(new HystrixCommandExecutionHook() {
@Override
public T onEmit(HystrixInvokable commandInstance, T value) {
String name = commandInstance.getClass().getSimpleName();
if (commandInstance.isFledExecution()) {
redisCache.incr(name + ".flure.count");
} else {
redisCache.incr(name + ".success.count");
}
return super.onEmit(commandInstance, value);
}
});
instanceFactories.add(new HystrixCommandExecutionHookApplicationFactory());
}
public class HystrixCommandExecutionHookApplicationFactory implements HystrixCommandExecutionHook {
@Override
public T onEmit(HystrixInvokable commandInstance, T value) {
String name = commandInstance.getClass().getSimpleName();
Long successCount = redisCache.get(name + ".success.count");
Long flureCount = redisCache.get(name + ".flure.count");
if (successCount == null || flureCount == null) {
return value;
}
Long totalCount = successCount + flureCount;
Integer flurePercent = Math.toIntExact(flureCount * 100 / totalCount);
if (flurePercent > 50) {
throw new RuntimeException("Circuit Breaker: " + name + " is Open");
}
return value;
}
}
}
配置文件中增加:
hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds: 60000
hystrix.command.default.metrics.rollingPercentile.numBuckets: 6
hystrix.command.default.fallbackIsolationSemaphoreMaxConcurrentRequests: 100
hystrix.command.default.circuitBreaker.requestVolumeThreshold: 20
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds: 5000
hystrix.command.default.circuitBreaker.errorThresholdPercentage: 50
基于Redis的限流
限流是指對服務(wù)的請求流量進(jìn)行控制,當(dāng)請求流量達(dá)到一定上限時(shí),系統(tǒng)將自動拒絕多余的請求,以保證服務(wù)的穩(wěn)定性和可靠性?;赗edis的限流通常是通過漏桶算法進(jìn)行實(shí)現(xiàn),即將請求放入一個“漏桶”中,利用Redis的List數(shù)據(jù)類型進(jìn)行存儲,通過pop操作來實(shí)現(xiàn)流量控制。
實(shí)現(xiàn)代碼如下:
public class RedisLeakyBucket {
private final StringRedisTemplate stringRedisTemplate;
public RedisLeakyBucket(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
private static final String KEY_PREFIX = "Limit:LeakyBucket:";
/**
* 添加元素
*
* @param key key
* @param element 元素
* @param rate 漏桶限流速率,單位:秒
* @param limit 桶的大小
*/
public synchronized boolean add(String key, String element, int rate, int limit) {
long now = System.currentTimeMillis();
stringRedisTemplate.opsForList().rightPush(key, now + "");
stringRedisTemplate.expire(key, rate, TimeUnit.SECONDS);
Long size = stringRedisTemplate.opsForList().size(key);
if (size > limit) {
stringRedisTemplate.opsForList().leftPop(key);
size--;
}
return size
}
}
調(diào)用時(shí):
@Autowired
private RedisLeakyBucket redisLeakyBucket;
public void test() {
boolean add = redisLeakyBucket.add("key", "element", 1, 100);
if (!add) {
throw new RuntimeException("拋出限流異常");
}
}
總結(jié)
本文主要介紹了如何使用Redis實(shí)現(xiàn)熔斷和限流兩個重要的微服務(wù)治理特性。熔斷和限流可以在一定程度上避免系統(tǒng)出現(xiàn)級聯(lián)宕機(jī)和性能瓶頸問題,提高系統(tǒng)的穩(wěn)定性和可靠性。同時(shí)Redis提供了非常方便和高效的數(shù)據(jù)類型和命令,可以實(shí)現(xiàn)對服務(wù)的計(jì)數(shù)和限流控制。
香港服務(wù)器選創(chuàng)新互聯(lián),2H2G首月10元開通。
創(chuàng)新互聯(lián)(www.cdcxhl.com)互聯(lián)網(wǎng)服務(wù)提供商,擁有超過10年的服務(wù)器租用、服務(wù)器托管、云服務(wù)器、虛擬主機(jī)、網(wǎng)站系統(tǒng)開發(fā)經(jīng)驗(yàn)。專業(yè)提供云主機(jī)、虛擬主機(jī)、域名注冊、VPS主機(jī)、云服務(wù)器、香港云服務(wù)器、免備案服務(wù)器等。
當(dāng)前名稱:基于Redis優(yōu)雅實(shí)現(xiàn)熔斷與限流(redis熔斷和限流)
網(wǎng)頁URL:http://www.dlmjj.cn/article/cocpggc.html


咨詢
建站咨詢
