SpringCloud Zuul过滤器和谷歌Gauva实现限流

网友投稿 340 2023-06-18

SpringCloud Zuul过滤器和谷歌Gauva实现限流

SpringCloud Zuul过滤器和谷歌Gauva实现限流

前提:

已经配置Zuul网关

参考:

https://jb51-/article/182894.htm

限流方式:

1)nginx层限流

2)网关层限流

1.添加限流过滤器

import com.alibaba.fastjson.JSON;

import com.google.common.util.concurrent.RateLimiter;

import com-flix.zuul.ZuulFilter;

import com.necFDnLXCvutflix.zuul.context.RequestContext;

import com-flix.zuul.exception.ZuulException;

import org.apache.commons.lang.StringUtils;

import org.springframework.http.HttpStatus;

import org.springframework.stereotype.Component;

import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import static org.springframework.cloud-flix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**

* 订单限流接口

*/

@Component

public class OrderRateLimiterFilter extends ZuulFilter {

//每秒产生1000个令牌

private static final RateLimiter RATE_LIMITER = RateLimiter.create(1000);

@Override

public String filterType() {

return PRE_TYPE;

}

@Override

public int filterOrder() {

return -4;

}

@Override

public boolean shouldFilter() {

RequestContext context = RequestContext.getCurrentContext();

HttpServletRequest request = context.getRequest();

///apigateway/order/api/v1/order/test

System.out.println(request.getRequestURI());

//http://127.0.0.1:9000/apigateway/order/api/v1/order/test

System.out.println(request.getRequestURL());

//限流的接口

List noFIlter = new ArrayList<>();

noFIlter.add("/apigateway/order/**");

AntPathMatcher matcher = new AntPathMatcher();

for (String pattern : noFIlter) {//pattern--/user/**

if (StringUtils.isNotEmpty(pattern)

&& matcher.match(pattern, request.getRequestURI())) {

return true;

}

}

return false;

}

@Override

public Object run() throws ZuulException {

//可以用JMeter来进行测试

RequestContext context = RequestContext.ghttp://etCurrentContext();

//tryAcquire达到最大流量时,立刻限流,也可以配置参数

if (!RATE_LIMITER.tryAcquire()) {

Map result = new HashMap<>();

result.put("code", 429);

result.put("msg", "目前访问量过大,限流了...");

context.setSendZuulResponse(false);

context.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());

context.setResponseBody(JSON.toJSONStcFDnLXCvuring(result));

//解决中文乱码

context.getResponse().setCharacterEncoding("UTF-8");

context.getResponse().setContentType("text/html;charset=UTF-8");

}

return null;

}

}

令牌桶限流图解

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring mvc Controller和RestFul原理解析
下一篇:SpringCloud可视化链路追踪系统Zipkin部署过程
相关文章

 发表评论

暂时没有评论,来抢沙发吧~