首页 > 解决方案 > Spring WebFlux 中的 SessionLocaleResolver 等效项 - 通过会话数据解析语言环境

问题描述

如果我们需要从会话数据中解析语言环境值,我们如何在 Spring WebFlux 中以响应式的方式实现呢?

对于非反应式 Web 应用程序,SessionLocaleResolver可用于从会话数据中解析语言环境。

对于 Spring WebFlux,拦截语言环境解析器的方法是使用LocaleContextResolver. Spring Boot WebFlux starter 中提供的默认实现是AcceptHeaderLocaleContextResolver. 这个接口的问题是它只提供了同步方法resolveLocaleContext(ServerWebExchange)。如果我需要从请求查询参数或Accept-Language标头中解析语言环境,它可以完美运行,因为ServerWebExchange它提供了访问请求对象的直接方法,而请求对象又提供了直接访问参数和标头的方法。

override fun resolveLocaleContext(exchange: ServerWebExchange): LocaleContext {
    val langParams = exchange.request.queryParams["lang"]
    var targetLocale: Locale? = null
    if (langParams != null && langParams.isNotEmpty()) {
        for (lang in langParams) {
            val locale = Locale.forLanguageTag(lang)
            if (locale != null) {
                targetLocale = locale
                break
            }
        }
    }
    return SimpleLocaleContext(targetLocale ?: Locale.forLanguageTag("en-US"))
}

但是,如果我需要从会话数据中解析语言环境,就会出现问题。ServerWebExchange#getSession()返回Mono<WebSession>。除非我调用Mono#block(). 然而,这不是一种理想的、被动的方式。

有没有办法解决这个问题?或者春天有什么计划来改变这个吗?

(之前有一个类似的问题被埋没了:Spring WebFlux - SessionLocaleResolver

标签: springspring-bootspring-webflux

解决方案


推荐阅读