日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java的rest异步调用_使用AsyncRestTemplate进行异步调用

發布時間:2024/3/24 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java的rest异步调用_使用AsyncRestTemplate进行异步调用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

背景:

最近項目中需要并發調用c++服務的http接口,問題是同時調用兩個接口時,會發生嚴重阻塞,導致頁面響應慢,還經常遇到接收數據超時,導致RestTemplate報出ReadTimeout錯誤,一味地增加ReadTimeout時間解決不了根本問題。

原使用的方案:

前一個版本中使用的是Feign,雖然響應速度方面還可以,但是唯一不足是,返回的數據只能以String接收,在每一個方法中進行String轉換成java對象的方法。

我是一個比較懶的程序員,不想寫很多無用的重復代碼。所以在這次版本中決定使用RestTemplate,封裝一個RestClient工具類,所有調用第三方接口都通過該工具類提供的方法調用,返回的ResponseEntity通過指定的Class類型進行轉換并返回。

解決方案:

使用AsyncRestTemplate異步調用接口,無阻塞進行請求。下面直接貼代碼。

一、AsyncRestTemplate注冊為Bean,使Spring容器對其進行管理。

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.client.AsyncRestTemplate;

@Configuration

public class RestTemplateConfiguration {

@Bean

public AsyncRestTemplate asyncRestTemplate() {

return new AsyncRestTemplate();

}

}

此次采用的是AsyncRestTemplate默認的構造方法。會默認使用SimpleAsyncTaskExecutor。

二、編寫測試Controller類

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.util.concurrent.ListenableFuture;

import org.springframework.util.concurrent.ListenableFutureCallback;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.client.AsyncRestTemplate;

@RestController

public class WebController {

@Autowired

private AsyncRestTemplate asyncRestTemplate;

@RequestMapping("/demo")

public String demo() {

try {

Thread.sleep(30000);

} catch (Exception e) {

e.printStackTrace();

}

return new Date()+"--->>>30秒。。。。";

}

@RequestMapping("/async")

public String async() {

String url = "http://127.0.0.1:8080/demo";

//調用完后立即返回(沒有阻塞)

ListenableFuture> forEntity = asyncRestTemplate.getForEntity(url, String.class);

//異步調用后的回調函數

forEntity.addCallback(new ListenableFutureCallback>() {

//調用失敗

@Override

public void onFailure(Throwable ex) {

System.err.println("=====rest response faliure======");

}

//調用成功

@Override

public void onSuccess(ResponseEntity result) {

System.out.println("--->async rest response success----, result = "+result.getBody());

}

});

return new Date()+"--->>>異步調用結束";

}

}

三、調用async接口

16:15:20先返回異步調用結束

而調用的方法時16:15:50,即休眠30秒后返回的。

僅供參考,后期對AsyncRestTemplate有更深入的了解繼續更新。。。

總結

以上是生活随笔為你收集整理的java的rest异步调用_使用AsyncRestTemplate进行异步调用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。