AsyncRestTemplate异步请求,这个的异步请求简单多了

167 阅读1分钟

在写项目过程中或多或少会跟其他项目联调数据,互相传数据,有时在测试自己项目性能时候发现调别的项目接口传输数据可能慢,影响自己的项目性能。在只频繁需要传输数据不需要对方回令情况可以使用AsyncRestTemplate,代码如下

public static void main(String[] args) throws Exception {
    long l = System.currentTimeMillis();
    AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
    JSONObject jo = new JSONObject();
    jo.put("name","liu");

    HttpEntity<String> httpEntity = new HttpEntity<>(null);
    for (int i = 0; i < 10000; i++) {
        jo.put("id",i);
        String msg =String.valueOf(jo);
        String url ="http://localhost:9001/user/isMember?user="+msg;
        asyncRestTemplate.postForLocation(url, httpEntity,msg);
    }
    System.out.println("消耗时间:"+(System.currentTimeMillis()-l));
}

为什么写这一个原因,因为我一般在传输少量字段时候喜欢用get请求,多个字段我喜欢红post请求传对象,但是有一些人在用下列方法代码

@PostMapping("/isMember")
public boolean isMember(@RequestParam(required = true) String user){
    System.out.println("isMember-->"+user);
    //逻辑处理。。。

    return false;
}

asyncRestTemplate.postForLocation(url, httpEntity,msg);这个方法如果你没有使用的话,你使用的是asyncRestTemplate.exchange(url, HttpMethod.POST,httpEntity,String.class); 你一定要注意如果你传的参数是集合或对象转化的字符串会报错:Exception in thread "main" java.lang.IllegalArgumentException: Not enough variable values available to ex

snipaste_20231015_194742.png 正确的方法应该是

String url ="http://localhost:9001/user/isMember?userId={111}";
//asyncRestTemplate.postForLocation(url, httpEntity,msg);
//asyncRestTemplate.exchange(url,HttpMethod.POST,httpEntity,String.class);
asyncRestTemplate.exchange(url,HttpMethod.POST,httpEntity,String.class,msg);

毕竟向别人传数据时,别人提供接口,接口是别人写的,咱们应该按照别人的接口来传数据,毕竟人家已经提供接口,你传不到给他就是网络或者你的问题。 AsyncRestTemplate方法是我见过最简单的异步请求方法了,其他的异步请求有一些麻烦,如果兄弟们有跟简单方便的异步http请求可以提出来