Http请求及单个接口限流

package com.firefly.performance.core.utils;

import com.alibaba.nacos.common.utils.StringUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhangping
 */
@Slf4j
public class HttpClientUtil {

    /**
     * http get请求x-www-form-urlencoded入参
     * @param url
     * @param map
     * @return
     */
    public static String get(String url, Map<String,Object> map){
        if(StringUtils.isEmpty(url)){
            return null;
        }
        StringBuffer responseSB = new StringBuffer();
        if(Objects.nonNull(map) && map.size() > 0){
            String param = "";
            for(String key :map.keySet()){
                param += "&" + key + "=" + map.get(key);
            }
            param = param.replaceFirst("&","?");
            url = url + param;
        }
        // 目标地址
        HttpGet httpGet = new HttpGet(url);

        // 设置类型 "application/x-www-form-urlencoded" "application/json"
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
        log.info("调用URL: " + httpGet.getURI());
        try(CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));){
            String line;
            responseSB = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                responseSB.append(line);
            }
            log.info("返回消息:" + responseSB);
            response.getEntity();
        }catch (Exception e){
            log.info("调用get请求异常 {}", e);
        }
        return responseSB.toString();
    }

    /**
     * HttpPost请求
     * @param url
     * @param jsonData
     * @return
     */
    public static String post(String url,String jsonData) {
        String result = "";
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        //创建httpclient对象

        try (CloseableHttpClient httpClient = HttpClients.createDefault()){
            BasicResponseHandler handler = new BasicResponseHandler();
            //设置请求格式
            //解决中文乱码问题
            StringEntity entity = new StringEntity(jsonData, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            //执行POST请求
            result = httpClient.execute(httpPost, handler);
            return result;
        } catch (Exception e) {
            log.info("HttpPost请求异常:{}",e);
        }
        return result;
    }

    /*public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>();
        map.put("todoBatchNo","jx-1682233176188");
        map.put("source","绩效");
        get("http://appuat.mirrorftech.com/unToken/msg/todo/send/uniformly",map);
    }*/

    /**
     * 单个接口限流使用[限制说明:5秒钟内请勿重复请求]
     */
    private static final LoadingCache<String, AtomicLong> counter = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build(new CacheLoader<String, AtomicLong>() {
        @Override
        public AtomicLong load(String s) {
            return new AtomicLong(0);
        }
    });

    /**
     * 访问限制-重复请求
     * @param serializableNo
     */
    public static void restrictingAccess(String serializableNo) {
        Assert.fail(StringUtils.isEmpty(serializableNo),"前端随机字符串不能为空!");
        try {
            if(counter.get(serializableNo).incrementAndGet() > 1) {
                //被限流了 Do Nothing 10秒钟内请勿重复请求
                Assert.fail(Boolean.TRUE,"当前请求频繁,请稍后再试!");
            }
        } catch (ExecutionException e) {
            log.info("接口限流方法异常:{}",e);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值