当前位置 : 主页 > 编程语言 > java >

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

来源:互联网 收集:自由互联 发布时间:2021-05-10
前提: 已经配置Zuul网关 参考: https://www.jb51.net/article/182894.htm 限流方式: 1)nginx层限流 2)网关层限流 1.添加限流过滤器 import com.alibaba.fastjson.JSON;import com.google.common.util.concurrent.Rate

前提:

已经配置Zuul网关

参考:

https://www.jb51.net/article/182894.htm

限流方式:

1)nginx层限流

2)网关层限流

1.添加限流过滤器

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.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.netflix.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<String> 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.getCurrentContext();
    //tryAcquire达到最大流量时,立刻限流,也可以配置参数
    if (!RATE_LIMITER.tryAcquire()) {
      Map<String, Object> result = new HashMap<>();
      result.put("code", 429);
      result.put("msg", "目前访问量过大,限流了...");

      context.setSendZuulResponse(false);
      context.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
      context.setResponseBody(JSON.toJSONString(result));
      //解决中文乱码
      context.getResponse().setCharacterEncoding("UTF-8");
      context.getResponse().setContentType("text/html;charset=UTF-8");
    }

    return null;
  }
}

令牌桶限流图解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

网友评论