sentinel使用教程1

本文介绍使用Alibaba Sentinel实现资源保护的方法,包括通过QPS限流、异常比率及响应时间来触发降级策略。提供了详细的代码示例,演示如何配置及应用这些规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.demo;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * description
 *
 * @author xichengxml
 * @date 2020-10-27 15:28:02
 */
@Slf4j
public class SentinelTest {

	static {
		SentinelUtils2.load();
	}

	public static void main(String[] args) throws Exception {
		// testFail();
		// testTimeFail();
		testQps();
	}

	private static void testQps() throws Exception {
		// SentinelUtils.initDegradeRule("testQps");
		while (true) {
			Entry entry = null;
			try {
				TimeUnit.MILLISECONDS.sleep(40);
				entry = SphU.entry("testQps");
				/*您的业务逻辑 - 开始*/
				log.info("testQps");
				/*您的业务逻辑 - 结束*/
			} catch (BlockException e1) {
				/*流控逻辑处理 - 开始*/
				log.info("block!");
				/*流控逻辑处理 - 结束*/
			} finally {
				if (entry != null) {
					entry.exit();
				}
			}
		}
	}

	private static void testFail() throws Exception {
		SentinelUtils.initDegradeRule("testFail");
		Entry entry = null;
		while (true) {
			try {
				TimeUnit.MILLISECONDS.sleep(40);
				entry = SphU.entry("testFail");
				new Thread(SentinelTest::mockRpcInvokeFail).start();
			} catch (BlockException e) {
				log.info("block");
			} finally {
				if (null != entry) {
					entry.exit();
				}
			}
		}
	}

	private static void mockRpcInvokeFail() {
		// 模拟50%的失败率
		long count = Thread.currentThread().getId() % 2;
		if (count == 0) {
			throw new RuntimeException("fail");
		} else {
			log.info("failMethod");
		}
	}

	private static void testTimeFail() throws Exception {
		long startTime = System.currentTimeMillis();
		SentinelUtils.initDegradeRule("testTimeFail");
		log.info("init runTime: {}", System.currentTimeMillis() - startTime);
		Entry entry = null;
		while (true) {
			TimeUnit.MILLISECONDS.sleep(40);
			try {
				entry = SphU.entry("testTimeFail");
				new Thread(SentinelTest::mockRpcTimeout).start();
			} catch (BlockException e) {
				log.info("block");
			} finally {
				if (null != entry) {
					entry.exit();
				}
			}
		}

	}

	private static void mockRpcTimeout() {
		// 超时2s,模拟50%的超时率
		long count = Thread.currentThread().getId() % 4;
		log.info("mockTimeFail");
		try {
			TimeUnit.SECONDS.sleep(count);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

package com.example.demo;

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.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SentinelUtils简介
 * @author xichengxml
 * @date 2020-10-28 11:20
 */
@Slf4j
public class SentinelUtils {

	private static final int TIME_WINDOW = 5;

	private static final Set<String> KEY_SET = ConcurrentHashMap.newKeySet();

	/**
	 * 降级规则
	 *
	 * @param key 资源
	 */
	public static void initDegradeRule(String key) {
		// 判断这个方法是否已经启动规则
		if (KEY_SET.contains(key)) {
			return;
		}
		synchronized (SentinelUtils.class) {
			if (KEY_SET.contains(key)) {
				return;
			}
			List<DegradeRule> rules = DegradeRuleManager.getRules();
			DegradeRule degradeRuleTime = buildDegradeRule(key, RuleConstant.DEGRADE_GRADE_RT, 1000D);
			rules.add(degradeRuleTime);

			// 异常比例
			DegradeRule degradeRuleRadio = buildDegradeRule(key, RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO, 0.3);
			rules.add(degradeRuleRadio);

			List<FlowRule> flowRules = new ArrayList<>();
			FlowRule flowRule = buildFlowRule(key);
			flowRules.add(flowRule);
			DegradeRuleManager.loadRules(rules);
			FlowRuleManager.loadRules(flowRules);
			KEY_SET.add(key);
		}
	}

	private static FlowRule buildFlowRule(String key) {
		FlowRule rule = new FlowRule();
		rule.setResource(key);
		rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
		// Set limit QPS to 20.
		rule.setCount(20);
		return rule;
	}

	private static DegradeRule buildDegradeRule(String key, int degradeGradeRt, Double timeCount) {
		DegradeRule degradeRuleTime = new DegradeRule();
		degradeRuleTime.setResource(key);
		degradeRuleTime.setGrade(degradeGradeRt);
		degradeRuleTime.setCount(timeCount);
		degradeRuleTime.setTimeWindow(TIME_WINDOW);
		return degradeRuleTime;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值