2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SpringWebflux/Kotlin】手動でトランザクションを有効にして処理を行う【R2DBC】

Last updated at Posted at 2022-08-27

TL;DR

  • TransactionalOperator.transactionalを使うと簡単
    • 処理の中でのsuspend関数呼び出しはmono関数でラップするのが簡単

やり方

サンプルコードは以下の通りです。

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.mono
import org.springframework.stereotype.Component
import org.springframework.transaction.reactive.TransactionalOperator

@Component
class TransactionOperation(private val transactionalOperator: TransactionalOperator) {
    // 中にそのまま処理を書く場合
    suspend fun operation() {
        transactionalOperator
            .transactional(
                mono {
                    /* ここにやりたい処理(DBアクセスを行うsuspend関数の呼び出しなど)を書く */
                }
            ).awaitSingle()
    }
}

Kotlinから扱いやすくするため、以下のようなutilを用意するのもおすすめです。

// Tそのものは上界無指定 = nullableだが、awaitSingleOrNullがT?を返してしまうため、キャストしている
@Suppress("UNCHECKED_CAST")
suspend fun <T> TransactionalOperator.transactional(block: suspend CoroutineScope.() -> T): T =
    transactional(mono(block = block)).awaitSingleOrNull() as T

// 以下のように利用できる
suspend fun foo() { /* トランザクション内で実行したい処理 */ }
suspend fun bar() {
    // トランザクションを有効にしてfooを呼び出す
    transactionalOperator.transactional { foo() }
}

TransactionalOperatorの取得について

TransactionalOperatorは、自分の環境ではAutowireして利用できました。
また、ReactiveTransactionManagerから生成することもできます

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?