如何在SpringWebsocket中为@Header值创建自定义转换器/反序列化程序



我有一个Websocket端点,我想接收它作为头值,而不是字符串,而是对象。

这就是我定义websocket端点的方式

@MessageMapping("/gather/{resource}")
fun emitGatherEvent(@DestinationVariable resource: String, @Header context: Context) {     
LOG.debug("gather endpoint called for client ${context.clientId} and character ${context.characterId} with resource '$resource'")
eventDispatcher.dispatchEvent(Gather(resource), context.characterId)
}

然而,Spring抛出了一个例外:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [@org.springframework.messaging.handler.annotation.Header com.barbarus.gameserver.websocket.Context]

我理解这个问题,但我不知道如何为Context数据类注册自定义转换器。

知道怎么做吗?

您可以通过FormatterRegistry执行此操作

@Configuration
public class YourConfig implements WebMvcConfigurer{
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new YourCustomConverter());
}
}

}

最新更新