文章目录
- 一、自定义限流处理
- 1. 自定义处理类
- 2. 请求一次测试
- 3. 重新配置流控规则
- 4. 重新测试
- 5. controller
- 二、方法限流处理
- 2.1. 创建接口
- 2.2. 创建接口实现类
- 2.3. 接口调用
- 2.4. 请求
- 2.5. 设置流控规则
一、自定义限流处理
自定义限流文档
1. 自定义处理类
package com.gblfy.distributedlimiter.handle;import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.gblfy.distributedlimiter.enums.ServiceErrCode;
import com.gblfy.distributedlimiter.exception.BaseServiceException;
import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** Springboot自定义全局异常类返回json* https://www.cnblogs.com/maolinjava/archive/2018/12/28/10193280.html*/
@Component
public class LimiterBlockHandler implements BlockExceptionHandler {@Overridepublic void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {//如果超过流控管理的就抛出异常throw new BaseServiceException(ServiceErrCode.REQ_PARAM_ERR.getMsg(), ServiceErrCode.REQ_PARAM_ERR);}
}
//这里采用了返回json
2. 请求一次测试
由于sentinel流控规则存在内存中,springboot项目重启,流控规则就没了,需要重新设置,下面会重点解决此问题
http://localhost:8082/sentinel
3. 重新配置流控规则
4. 重新测试
http://localhost:8082/sentinel
请求数量>1
5. controller
package com.gblfy.distributedlimiter.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class SentinelLimiterController {@GetMapping("/sentinel")public String sentinel() {return "sentinel";}
}
Springboot全局异常统一处理返回json
https://gblfy.blog.csdn.net/article/details/113824175
二、方法限流处理
2.1. 创建接口
package com.gblfy.distributedlimiter.service;public interface LimiterService {public String process();
}
2.2. 创建接口实现类
package com.gblfy.distributedlimiter.service.impl;import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.gblfy.distributedlimiter.service.LimiterService;
import org.springframework.stereotype.Service;@Service
public class LimiterServiceImpl implements LimiterService {@Override@SentinelResource("LimiterService.process")//自定义埋点public String process() {return "process";}
}
2.3. 接口调用
package com.gblfy.distributedlimiter.controller;import com.gblfy.distributedlimiter.service.LimiterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class SentinelLimiterController {@Autowiredprivate LimiterService limiterService;@GetMapping("/sentinel")public String sentinel() {return limiterService.process();}
}
2.4. 请求
http://localhost:8082/sentinel
2.5. 设置流控规则
具体信息相见文档,后续补充
https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme-zh.md