稍后获取
适用于 ✅ 开源版 ✅ 专业版 ✅ 企业版
使用 Java 8 CompletableFutures
Java 8 引入了新的 java.util.concurrent.CompletableFuture
类型,它允许异步执行单元的函数式组合。将其应用于 SQL 和 jOOQ 时,您可以编写如下代码
// Initiate an asynchronous call chain CompletableFuture // This lambda will supply an int value indicating the number of inserted rows .supplyAsync(() -> DSL.using(configuration) .insertInto(AUTHOR, AUTHOR.ID, AUTHOR.LAST_NAME) .values(3, "Hitchcock") .execute() ) // This will supply an AuthorRecord value for the newly inserted author .handleAsync((rows, throwable) -> DSL.using(configuration) .fetchOne(AUTHOR, AUTHOR.ID.eq(3)) ) // This should supply an int value indicating the number of rows, // but in fact it'll throw a constraint violation exception .handleAsync((record, throwable) -> { record.changed(true); return record.insert(); }) // This will supply an int value indicating the number of deleted rows .handleAsync((rows, throwable) -> DSL.using(configuration) .delete(AUTHOR) .where(AUTHOR.ID.eq(3)) .execute() ) .join();
上面的示例将依次执行四个操作,但在 JDK 的默认或公共 java.util.concurrent.ForkJoinPool
中异步执行。
有关更多信息,请参阅 java.util.concurrent.CompletableFuture
Javadoc 和官方文档。
使用已弃用的 API
有些查询执行时间很长,但对于主程序的继续执行而言并非至关重要。例如,您可能正在 Swing 应用程序中生成复杂的报告,并且在数据库中计算此报告时,您希望显示后台进度条,允许用户继续进行其他工作。这可以通过 jOOQ 简单地实现,方法是创建一个 org.jooq.FutureResult
,这是一种扩展 java.util.concurrent.Future
的类型。下面给出一个例子
// Spawn off this query in a separate process: FutureResult<BookRecord> future = create.selectFrom(BOOK).where(... complex predicates ...).fetchLater(); // This example actively waits for the result to be done while (!future.isDone()) { progressBar.increment(1); Thread.sleep(50); } // The result should be ready, now Result<BookRecord> result = future.get();
请注意,除了让 jOOQ 派生一个新线程之外,您还可以向 jOOQ 提供您自己的 java.util.concurrent.ExecutorService
// Spawn off this query in a separate process: ExecutorService service = // [...] FutureResult<BookRecord> future = create.selectFrom(BOOK).where(... complex predicates ...).fetchLater(service);
反馈
您对此页面有任何反馈吗? 我们很乐意听到您的意见!