关于Unirest的使用问题

版本
Unirest目前版本类型

        <dependency>
            <groupId>com.mashape.unirest</groupId>
            <artifactId>unirest-java</artifactId>
            <version>1.4.9</version>
        </dependency>
       <dependency>
            <groupId>com.konghq</groupId>
            <artifactId>unirest-java</artifactId>
            <version>3.14.1</version>
        </dependency>

可以看groupId的不同 com.mashape.unirest 和 com.konghq 两个维护团队吧

主要说一下项目中使用unirest的mashape版本问题
com.mashape.unirest版本的unirest现在基本属于不维护状态的, 设置请求超时时间和响应时间上
错误代码

    Unirest.setConcurrency(60000,60000);
    HttpResponse<String> stringHttpResponse;
    try {
        String url = "http://localhost:8080/youzan/test1" ;
        Map<String, String> header = new HashMap<>();
        header.put("Accept", "application/json, text/plain, */*");
        header.put("Connection", "keep-alive");
        header.put("Content-Type", "application/json;charset=UTF-8");
        stringHttpResponse = Unirest.get(url).headers(header).asString();
    }catch(Exception e) {
        throw new RuntimeException(e);
    }

这样请求会引发的结果就是大量请求出现服务会直接oom



通过jdk自带工具jvisual可以查看实时内存情况, 或者打印出堆栈日志,记录信息

我们看一下Unirest源码这部分内容



在每次的调用过程中他都会启动一个SyncIdleConnectionMonitorThread的线程类
并且线程不会停止,一直处于wait状态, 最终导致内存溢出的情况

老版本使用策略

static { Unirest.setTimeouts(60000,60000); }
使用静态代码块全局只加载一次, 又或者放到启动类中随着服务启动进行加载设置.

新版本 com.konghq

这个版本解决的之前版本的问题, 配置了默认超时时间, 但是也可以手动进行初始化配置更改
这个版本强制配置初始化一次, 多次会出现服务异常
一般情况下我们可以不用设置, 可以直接开箱使用, 配置设置 Unirest.config().socketTimeout(500).socketTimeout(500);
可以具体看一下Unirest这款轻量化http框架, 也有很多的功能!

posted @ 2023-03-03 00:31  freedomlog  阅读(611)  评论(0编辑  收藏  举报