【Sentinel的限流使用】⭐️SpringBoot整合Sentinel实现Api的限流
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class SentinelController {
@GetMapping("/test")
@SentinelResource(value = "test", blockHandler = "handleException")
public String test() {
return "Test API is called";
}
public String handleException(BlockException ex) {
return "Sorry, the API is blocked due to too many requests";
}
}
这段代码演示了如何在Spring Boot应用中使用Sentinel的注解来实现对API方法的限流,并指定了限流时的异常处理方法。通过@SentinelResource
注解定义了资源名称,并通过blockHandler
属性指定了限流时的处理函数。
评论已关闭