🍟 异步请求
# 设置异步/同步
在Forest使用异步请求,可以通过设置@Request
注解的async
属性为true
实现,不设置或设置为false
即为同步请求
/**
* async 属性为 true 即为异步请求,为 false 则为同步请求
* 不设置该属性时,默认为 false
*/
@Get(
url = "http://localhost:8080/hello/user?username=${0}",
async = true
)
String asyncGet(String username);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 使用回调函数
异步请求的方法无法直接通过返回值接受服务端响应的结果,因为在网络还在没完成连接和响应的过程中,方法已经返回了
此时需要成功/失败回调函数来响应网络请求的结果
@Get(
url = "http://localhost:8080/hello/user?username=${0}",
async = true,
headers = {"Accept:text/plain"}
)
void asyncGet(String username, OnSuccess<String> onSuccess, OnError onError);
1
2
3
4
5
6
2
3
4
5
6
一般情况下,异步请求都通过OnSuccess<T>
回调函数来接受响应返回的数据,而不是通过接口方法的返回值,所以这里的返回值类型一般会定义为void
。
文档导航
关于回调函数的使用请参见 《回调函数》
// 异步执行
myClient.asyncGet("foo", (result, req, res) -> {
// 请求成功,处理响应结果
System.out.println(result);
}, (ex, req, res) -> {
// 请求失败,处理失败信息
System.out.println(ex.getMessage());
});
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 使用 Future 接受异步数据
此外,若有些小伙伴不习惯这种函数式的编程方式,也可以用Future<T>
类型定义方法返回值的方式来接受响应数据。
@Request(
url = "http://localhost:8080/hello/user?username=foo",
async = true,
headers = {"Accept:text/plain"}
)
Future<String> asyncFuture();
1
2
3
4
5
6
2
3
4
5
6
这里Future<T>
类就是JDK
自带的java.util.concurrent.Future
类, 其泛型参数T
代表您想接受的响应数据的类型。
关于如何使用Future
类,这里不再赘述。
// 异步执行
Future<String> future = myClient.asyncFuture();
// 做一些其它事情
// 等待数据
String result = future.get();
1
2
3
4
5
6
7
2
3
4
5
6
7
帮助我们改善此文档 (opens new window)
上次更新: 2022/07/20, 22:33:22