Spring Websocket:如何拦截SimpMessagingTemplate通过任何convertAndSend或convertAndSendToUser方法发送的消息?

时间:2018-05-25 16:37:44

标签: spring spring-websocket

private final SimpMessagingTemplate simpMessagingTemplate; ... @Scheduled(cron="some expression") public void sendNotification() { logger.info("sendNotification ..."); simpMessagingTemplate.convertAndSend( "/topic/something", new Notification(...)); logger.info("... sendNotification"); }

我有以下情况并且工作正常:

Topic

代码工作正常。订阅ActiveMQ的所有客户(我正在使用@Component class MessageChannelInterceptorAdapter extends ChannelInterceptorAdapter { )都能看到发送的消息。

自定义类

@Override

创建所有方法MessageChannelInterceptorAdapter是为了拦截目的。

@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Autowired @Qualifier("messageChannelInterceptorAdapter") private ChannelInterceptorAdapter messageChannelInterceptorAdapter; ... @Override public void configureClientInboundChannel(ChannelRegistration registration) { registration.interceptors(messageChannelInterceptorAdapter); WebSocketMessageBrokerConfigurer.super.configureClientInboundChannel(registration); } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { registration.interceptors(messageChannelInterceptorAdapter); WebSocketMessageBrokerConfigurer.super.configureClientOutboundChannel(registration); } ... 类已在基础架构中注册如下:

SimpMessagingTemplate

即使应用程序运行良好。通过MessageChannelInterceptorAdapter发送的邮件永远不会被MessageChannelInterceptorAdapter拦截。

注意: Stomp类可以正常拦截SimpMessagingTemplate个事件,但不适用于SimpMessagingTemplate

这样:如何拦截convertAndSend通过convertAndSendToUser或{{1}}方法发送的任何邮件?

缺少什么?缺少有关基础结构的配置或创建扩展特定Spring类的其他类。

1 个答案:

答案 0 :(得分:0)

据我所知,没有简单的方法可以做到这一点。我遇到了直接调用模板的情况(像您一样)。当我迁移到使用外部STOMP代理时,突然发现我的某些呼叫不再有效:

使用Rabbit时,

/topic/sddf/traffic不再是有效的目的地

我开始考虑编写自己的类SimpMessagingTemplate的版本,这变得非常困难-因此,我不得不手动更改所有调用。

我的示例是在Kotlin中而不是Java

我的解决方案是使用此类:

@Component
@Configurable
class MessagingTemplateWrapper{

    var template: SimpMessagingTemplate = ApplicationContextHolder.getContext().getBean(SimpMessagingTemplate::class.java)
    private val log = LoggerFactory.getLogger(BridgeDataListener::class.java)

    fun convertAndSend(dest: String, data: Any) {

        val rabbitDestination = dest.substring(0,11) + dest.substring(11).replace("/",".")
        template.convertAndSend(rabbitDestination, data)
    }
}

在我使用模板的任何地方,我都这样做了:

//    var template: SimpMessagingTemplate = ApplicationContextHolder.getContext().getBean(SimpMessagingTemplate::class.java)
var template: MessagingTemplateWrapper = ApplicationContextHolder.getContext().getBean(MessagingTemplateWrapper::class.java)

所以我只是有一个包装来做(也许)你想要的。

我不喜欢这种解决方案-但它确实有效。

相关问题