guava限流

<!--google guava 限流-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>

package com.yung.user.util;

import com.google.common.util.concurrent.RateLimiter;
import com.yung.user.dto.HttpResult;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * http请求工具类
 */
public class HttpUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    private static final String URL_PARAM_CONNECT_EQUAL_SIGN = "=";
    private static final String URL_PARAM_CONNECT_FLAG = "&";
    private static final String HTTP_CONTENT_TYPE_KEY = "ContentType";

    private static MultiThreadedHttpConnectionManager connectionManager = null;
    /**
     * 连接超时时间
     */
    private static int connectionTimeOut = 2000;
    /**
     * 响应超时时间
     */
    private static int socketTimeOut = 2000;
    /**
     * 最大连接数
     */
    private static int maxConnectionPerHost = 30;
    /**
     * 最大活动连接数
     */
    private static int maxTotalConnections = 30;

    private static HttpClient client;

    /**
     * 令牌桶限流
     * 每秒产生300个令牌
     */
    private static RateLimiter rateLimiter = RateLimiter.create(300);

    static {
        connectionManager = new MultiThreadedHttpConnectionManager();
        connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
        connectionManager.getParams().setSoTimeout(socketTimeOut);
        connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
        connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
        client = new HttpClient(connectionManager);
    }

    /**
     * POST方式提交数据
     * @param url    待请求的URL
     * @param params 要提交的数据
     * @return 响应结果
     */
    public static HttpResult doPost(String url, Map<String, String> params) {
        //1秒没有获取令牌则 拒绝访问
        if (!rateLimiter.tryAcquire(1, TimeUnit.SECONDS)) {
            throw new BusinessException(ErrorStatus.GET_LIMIT_TOKEN_FAIL_ERROR);
        }

        HttpResult result = new HttpResult();
        PostMethod postMethod = null;
        try {
            postMethod = new PostMethod(url);
            if (StringUtils.isEmpty(params.get(HTTP_CONTENT_TYPE_KEY))) {
                postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF8");
            }

            if (MapUtils.isNotEmpty(params)) {
                Set<Map.Entry<String, String>> entries = params.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    postMethod.addParameter(entry.getKey(), entry.getValue());
                }
            }

            client.executeMethod(postMethod);
            result.setStatusCode(postMethod.getStatusCode());
            result.setData(postMethod.getResponseBodyAsString());
        } catch (HttpException e) {
            LOGGER.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
        } catch (IOException e) {
            LOGGER.error("发生网络异常", e);
        } finally {
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }
        return result;
    }


    /**
     * GET方式提交数据
     * @param url    待请求的URL
     * @param params 要提交的数据
     * @return 响应结果
     */
    public static HttpResult doGet(String url, Map<String, String> params) {
        //1秒没有获取令牌则 拒绝访问
        if (!rateLimiter.tryAcquire(1, TimeUnit.SECONDS)) {
            throw new BusinessException(ErrorStatus.GET_LIMIT_TOKEN_FAIL_ERROR);
        }

        HttpResult result = new HttpResult();
        GetMethod getMethod = null;

        String httpGetParamsStr = getHttpGetParamsStr(params);
        if (StringUtils.isNotEmpty(httpGetParamsStr)) {
            url = url + "?" + httpGetParamsStr;
        }
        try {
            getMethod = new GetMethod(url);
            if (StringUtils.isEmpty(params.get(HTTP_CONTENT_TYPE_KEY))) {
                getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF8");
            }

            client.executeMethod(getMethod);
            result.setStatusCode(getMethod.getStatusCode());
            result.setData(getMethod.getResponseBodyAsString());
        } catch (HttpException e) {
            LOGGER.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
        } catch (IOException e) {
            LOGGER.error("发生网络异常", e);
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
        }

        return result;
    }

    /**
     * 获取get请求参数字符串
     * @param params
     * @return
     */
    private static String getHttpGetParamsStr(Map<String, String> params) {
        if (MapUtils.isEmpty(params)) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        int i = 0;
        for (Map.Entry<String, String> entry : entries) {
            builder.append(entry.getKey()).append(URL_PARAM_CONNECT_EQUAL_SIGN).append(entry.getValue());
            if (i != entries.size() - 1) {
                builder.append(URL_PARAM_CONNECT_FLAG);
            }
            i++;
        }
        return builder.toString();
    }
}

  

猜你喜欢

转载自www.cnblogs.com/zfzf1/p/10951446.html