栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于springboot 整合Redis实现令牌桶分布式API限流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于springboot 整合Redis实现令牌桶分布式API限流

这里简单说一下用Redis实现令牌桶算法的方法。

用户每一次访问请求的时候,从redis中获取一个令牌,如果拿到令牌了,就说明没有超出限制,就通过这个请求,相反如果拿不到令牌就拦截这个请求或者返回错误信息,下面是代码实现部分。

1.定义Redis限流规则类

public final class RRateLimiter {
	private String rediskey = "limit";
	private Long all_conut = 20L;//令牌的总数量
	private Long conut = 10L;//生产的令牌数量
	private Long time = 5L;//产生的令牌的时间间隔
	private TimeUnit timetype = TimeUnit.SECONDS;
	private ListOperations redis;
	private void start() {
		new Thread(() -> {
			try {
				while (true) {
					timetype.sleep(time);
					if(redis.size(rediskey)redis.rightPush(rediskey,UUID.randomUUID().toString().replace("-","")));
				}
			} catch(Exception e){}
		}).start();
	}
	public RRateLimiter(ListOperations list, String rediskey, Long conut, Long time,
			TimeUnit timetype) {
		this.rediskey = rediskey;
		this.conut = conut;
		this.time = time;
		this.timetype = timetype;
		this.redis = list;
		start();
	}
	public RRateLimiter(ListOperations redis) {
		this.redis = redis;
		start();
	}
	public synchronized boolean tryAcquire() {
			return redis.leftPop(rediskey)!=null?true:false;
	}
}

2.自定义注解拦截器

@Component
public class LimtiInterceptor implements HandlerInterceptor,HandlerMethodArgumentResolver{

	@Autowired
	private RRateLimiter rateLimiter;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if(!(handler instanceof HandlerMethod))return true;
		HandlerMethod handlers = (HandlerMethod)handler;
		RequestLimit requestLimit = handlers.getMethodAnnotation(RequestLimit.class);
		if(requestLimit==null)requestLimit = handlers.getBeanType().getAnnotation(RequestLimit.class);
		if(requestLimit==null)return true;
		if(rateLimiter.tryAcquire()){
			return true;
		}else{
			if(requestLimit.requesttype()==CODE){
				response.setStatus(requestLimit.status());
			}else if(requestLimit.requesttype()==MESSAGE){
				response.setContentType("application/json;charset=UTF-8");
				try(PrintWriter printWriter = response.getWriter()){
					printWriter.write(JSONObject.toJSonString(ResultUtil.resultErr(requestLimit.message())));
				}
			}
		}
		return false;
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(Token.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		if(parameter.hasParameterAnnotation(Token.class) && authentication!=null && authentication.getPrincipal()!=null){
//			JwtUser jwtUser = (JwtUser)authentication.getPrincipal();
//			if(parameter.getParameterType()==JwtUser.class)
//			return jwtUser;
//		}
		return authentication!=null?authentication.getPrincipal():null;
	}

}

3.自定义注解类,用于注释要限流的方法和类,如果放在类上面对类中所有接口都有限流作用

@documented
@Inherited
@Target({METHOD,TYPE})
@Retention(RUNTIME)
public @interface RequestLimit {
	enum REQUEST_TYPE{CODE,MESSAGE}
	String message() default "访问数率过快";
	int status() default 426;
	int count() default 10;
	TimeUnit type() default TimeUnit.SECONDS;
	REQUEST_TYPE requesttype() default REQUEST_TYPE.CODE;
}

4.自定Controller类测试自定义注解限流

@Api("用户Controller")
@CacheConfig(cacheNames = "users")
@RestController
@RequestMapping("user")
public class UserController extends baseController{

    @ApiOperation(value = "查看当前登陆的用户信息",httpMethod = "GET",response =ResultUtil.class)
    @RequestLimit(requesttype = REQUEST_TYPE.MESSAGE)
    @GetMapping(value="/getuser")
    public ResultUtil getuser(@Token UserMsg object){
		return ResultUtil.resultOK(object);
    }

}

5.打开浏览器访问http://localhost:8083/user/getuser

正常情况下访问接口返回当前的用户登陆信息

快速刷新浏览器会出现以下错误信息或者直接返回状态码

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/343104.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号