🍟 异步请求
# 设置异步/同步
在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
# 开启 Kotlin 协程
自1.5.27版本开始 Forest 支持 Kotlin 语言的协程特性,可以在发送异步请求的时候使用 Kotlin 协程代替 JVM 的线程池
在使用 Kotlin 协程之前,需要先确保可以使用 Kotlin 语言,并有以下依赖
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
    <version>1.6.20</version>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlinx</groupId>
    <artifactId>kotlinx-coroutines-core</artifactId>
    <version>1.6.2</version>
</dependency>
 1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: '1.6.20'
compile group: 'org.jetbrains.kotlinx', name: 'kotlinx-coroutines-core', version: '1.6.2'
 1
2
2
// Make sure to add code blocks to your code group
Forest 默认情况下,请求的异步模式为platform,即 JVM 平台自带的线程池
如果要启用 Kotlin 线程,需要将异步模式设置为kotlin_coroutine
forest:
  async-mode: kotlin_coroutine
 1
2
2
forest.async-mode=kotlin_coroutine
 1
Forest.config().setAsyncMode(ForestAsyncMode.KOTLIN_COROUTINE);
 1
// Make sure to add code blocks to your code group
帮助我们改善此文档  (opens new window)
  上次更新: 2024/12/26, 12:59:11