1

I am using Sentinel to limit the user request, this is a minimal reproduce about the Sentinel demo that did not make effect, this is the startup class:

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);
    }

}

and this is the init rate limit class:

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);
    }
}

and this is the controller that limit the user request:

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);
                }
            }
        }
    }

in this application, I want the user request 2 times in 86400 second, but did not work. the user request did not have any limit. why did this happen? what should I do to fixed this issue?

Dolphin
  • 29,069
  • 61
  • 260
  • 539

0 Answers0