package com.example.demo.aspect;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.example.demo.config.NacosConfig;
import com.example.demo.constants.SentinelConstants;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
/**
* 限流拦截器
*
* @author lzt
* */
@Aspect
@Component
public class SentinelAspect {
@Resource
public NacosConfig config;
@Pointcut("execution(* com.example.demo.service.SentinelTestService .*(..))")
public void demoAspect() {
}
@PostConstruct
private void init(){
//初始化 cmm 的 QPS 控制规则
//TODO setParamIdx(0)不太懂
ParamFlowRule rule = new ParamFlowRule(SentinelConstants.SENTINEL_KEY).setParamIdx(0) // 指定当前 rule 对应的热点参数索引
.setGrade(RuleConstant.FLOW_GRADE_QPS) // 限流的维度,该策略针对 QPS 限流
.setDurationInSec(1) // 限流的单位时间
.setCount(config.getQbs())
.setParamFlowItemList(new ArrayList<>());
ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
}
@Around("demoAspect()")
public Object check(ProceedingJoinPoint joinPoint) {
Object result=null;
Object[] values = joinPoint.getArgs();
String param = JSONUtil.toJsonStr(values[0]);
Entry entry=null;
try {
//TODO entry()里参数具体含义
entry= SphU.entry(SentinelConstants.SENTINEL_KEY, EntryType.IN,1,param);
}catch (BlockException e){
return "请求太过频繁";
}finally {
if (entry!=null){
entry.exit();
}
}
return null;
}
}
@Autowired
public NacosConfig config;
问题描述的不够清楚,可以把异常堆栈全部贴出来看看。楼上的回答是一种可能性,因为 @Resource 默认通过 ByName 的方式在 Spring 容器中寻找容器。如果没有刻意指定 NacosConfig 在Spring容器中的命名,则默认的 beanName 是 nacosConfig。
所以可以尝试改为
@Resource
public NacosConfig nacosConfig;