我正在使用Sentinel来限制用户请求,这是对没有生效的Sentinel demo的最小复现,这是启动类:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
这是初始速率限制类:
package com.example.demo;
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 org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class RateLimitInit implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
rateLimitImpl();
}
private void rateLimitImpl(){
List<ParamFlowRule> paramFlowRules = new ArrayList<>();
ParamFlowRule ruleAsk = new ParamFlowRule();
ruleAsk.setResource("ChatGPT-ask-per-user");
ruleAsk.setGrade(RuleConstant.FLOW_GRADE_QPS);
ruleAsk.setCount(2);
ruleAsk.setDurationInSec(86400);
paramFlowRules.add(ruleAsk);
ParamFlowRuleManager.loadRules(paramFlowRules);
}
}
这是限制用户请求的控制器:
package com.example.demo;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
@Api
@Slf4j
public class DemoController {
@GetMapping("/chat")
@ApiOperation(value = "get all", tags = "customer")
void login(){
Entry entry = null;
try {
entry = SphU.entry("ChatGPT-ask-per-user", EntryType.IN, 1, 1);
System.out.println("ddd");
} catch (BlockException ex) {
log.error("chat ask trigger limit", ex);
} finally {
if (entry != null) {
entry.exit(1, 1);
}
}
}
}
在此应用程序中,我希望用户在 86400 秒内请求 2 次,但没有成功。用户请求没有任何限制。为什么会这样?我应该怎么做才能解决这个问题?