我将 webflux 与 netty 和 jdbc 一起使用,因此我用以下方式包装了阻塞的jdbc操作:
static <T> Mono<T> fromOne(Callable<T> blockingOperation) {
return Mono.fromCallable(blockingOperation)
.subscribeOn(jdbcScheduler)
.publishOn(Schedulers.parallel());
}
阻塞操作将由 jdbcScheduler 处理,我希望其他管道将由 webflux事件循环调度程序处理。
如何获取webflux事件循环调度程序?
答案 0 :(得分:3)
我强烈建议您重新考虑技术选择。如果要使用仍在阻塞的jdbc,则不应使用webflux。这是因为webflux将在非阻塞堆栈中发光,但与Jdbc结合将成为瓶颈。性能实际上会下降。
答案 1 :(得分:0)
我同意@Vikram Rawat的用法,jdbc非常危险,主要是因为jdbc是强大的IO api,并且使用事件循环响应模型非常危险,因为从根本上说,阻塞所有服务器非常容易。
但是,即使是实验性的工作,我还是建议您继续关注R2DBC项目,该项目能够为SQL充分利用无阻塞api,我曾将其用作峰值,而且非常优雅。
我可以为您提供一个示例,该示例取自基于sprign boot 2.1和kotlin的github上我的家庭项目:
网页层
@Configuration
class ReservationRoutesConfig {
@Bean
fun reservationRoutes(@Value("\${baseServer:http://localhost:8080}") baseServer: String,
reservationRepository: ReservationRepository) =
router {
POST("/reservation") {
it.bodyToMono(ReservationRepresentation::class.java)
.flatMap { Mono.just(ReservationRepresentation.toDomain(reservationRepresentation = it)) }
.flatMap { reservationRepository.save(it).toMono() }
.flatMap { ServerResponse.created(URI("$baseServer/reservation/${it.reservationId}")).build() }
}
GET("/reservation/{reservationId}") {
reservationRepository.findOne(it.pathVariable("reservationId")).toMono()
.flatMap { Mono.just(ReservationRepresentation.toRepresentation(it)) }
.flatMap { ok().body(BodyInserters.fromObject(it)) }
}
DELETE("/reservation/{reservationId}") {
reservationRepository.delete(it.pathVariable("reservationId")).toMono()
.then(noContent().build())
}
}
}
存储库层:
class ReactiveReservationRepository(private val databaseClient: TransactionalDatabaseClient,
private val customerRepository: CustomerRepository) : ReservationRepository {
override fun findOne(reservationId: String): Publisher<Reservation> =
databaseClient.inTransaction {
customerRepository.find(reservationId).toMono()
.flatMap { customer ->
it.execute().sql("SELECT * FROM reservation WHERE reservation_id=$1")
.bind("$1", reservationId)
.exchange()
.flatMap { sqlRowMap ->
sqlRowMap.extract { t, u ->
Reservation(t.get("reservation_id", String::class.java)!!,
t.get("restaurant_name", String::class.java)!!,
customer, t.get("date", LocalDateTime::class.java)!!)
}.one()
}
}
}
override fun save(reservation: Reservation): Publisher<Reservation> =
databaseClient.inTransaction {
customerRepository.save(reservation.reservationId, reservation.customer).toMono()
.then(it.execute().sql("INSERT INTO reservation (reservation_id, restaurant_name, date) VALUES ($1, $2, $3)")
.bind("$1", reservation.reservationId)
.bind("$2", reservation.restaurantName)
.bind("$3", reservation.date)
.fetch().rowsUpdated())
}.then(Mono.just(reservation))
override fun delete(reservationId: String): Publisher<Void> =
databaseClient.inTransaction {
customerRepository.delete(reservationId).toMono()
.then(it.execute().sql("DELETE FROM reservation WHERE reservation_id = $1")
.bind("$1", reservationId)
.fetch().rowsUpdated())
}.then(Mono.empty())
}
我希望能为您提供帮助