java sync和async区别_java – Spring RestTemplate – async vs sync rest...

博主对比了同步和异步RestTemplate在执行多个GET请求时的性能,发现两者在2800ms左右的平均时间上表现相近,没有明显速度优势。测试中使用了ThreadPoolTaskExecutor进行异步调用。尽管期望异步调用更快,但结果并未体现出来。
摘要由CSDN通过智能技术生成

我编写了以下代码来测试同步RestTemplate和AsyncRestTemplate的性能.我只是在POSTMAN上手动运行了几次.

我们只是将10个引用传递给GET调用,以便我们可以返回10个链接:

RestTemplate – 同步并在2806ms返回:

ArrayList references = new ArrayList<>();

ArrayList links = new ArrayList<>();

RestTemplate restTemplate = new RestTemplate();

restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

for (int i = 0; i < 10; i++) {

ResponseEntity resource = restTemplate.getForEntity(references.get(i), String.class);

links.add(resource.getBody().toString());

}

RestTemplate – 异步并返回2794ms:

//Creating a synchronizedList so that when the async resttemplate returns, there will be no concurrency issues

List links = Collections.synchronizedList(new ArrayList());

//CustomClientHttpRequestFactory just extends SimpleClientHttpRequestFactory but disables automatic redirects in SimpleClientHttpRequestFactory

CustomClientHttpRequestFactory customClientHttpRequestFactory = new CustomClientHttpRequestFactory();

//Setting the ThreadPoolTaskExecutor for the Async calls

org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor pool = new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor();

pool.setCorePoolSize(5);

pool.setMaxPoolSize(10);

pool.setWaitForTasksToCompleteOnShutdown(true);

pool.initialize();

//Setting the TaskExecutor to the ThreadPoolTaskExecutor

customClientHttpRequestFactory.setTaskExecutor(pool);

ArrayList references = new ArrayList<>();

ArrayList links = new ArrayList<>();

AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(customClientHttpRequestFactory);

restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

for (int i = 0; i < 10; i++) {

Future> resource = asyncRestTemplate.getForEntity(references.get(i), String.class);

ResponseEntity entity = resource.get(); //this should start up 10 threads to get the links asynchronously

links.add(entity.getBody().toString());

}

在大多数情况下,两种方法实际上都以非常相似的时间返回结果,在异步和同步调用中平均为2800ms.

我做错了什么,因为我希望异步调用更快?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值