【问题标题】:How do I send a message in an Spring ApplicationListener (SessionConnectedEvent)如何在 Spring ApplicationListener (SessionConnectedEvent) 中发送消息
【发布时间】:2015-09-03 02:14:58
【问题描述】:

我使用 Stomp over SockJS 和 Spring 消息传递。当连接新用户时,我正在尝试向所有登录用户发送消息。所以首先这是我的听众:

@Component
public class SessionConnectedListener implements ApplicationListener<SessionConnectedEvent> {

    private static final Logger log = LoggerFactory.getLogger(SessionConnectedListener.class);

    @Autowired
    private SimpMessagingTemplate template;

    @Override
    public void onApplicationEvent(SessionConnectedEvent event) {
        log.info(event.toString());

        // Not sure if it's sending...?
        template.convertAndSend("/topic/login", "New user logged in");
    }

}

我的 WebSocket 配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("chat").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");
        config.setApplicationDestinationPrefixes("/app");
    }

}

我的 JS 配置

var socket = new SockJS('/chat');
stompClient = Stomp.over(socket);

stompClient.connect({}}, function(frame) {

    // ... other working subscriptions

    stompClient.subscribe("/topic/login", function(message) {
        console.log(message.body);
    });

});

我的问题是我的 template.convertAndSend()ApplicationListener 中不起作用。但是,如果我将它放在使用 @MessageMapping 注释的 Controller 方法中,它将起作用,并且我将拥有一个控制台日志客户端。

所以我的问题是:template.convertAndSend() 可以在 ApplicationListener 中工作吗?如果是这样,怎么做?还是我错过了什么?

感谢您的帮助!

PS : 我的 log.info(event.toString());在 ApplicationListener 中工作 所以我知道我正在进入 onApplicationEvent() 方法。

【问题讨论】:

    标签: spring spring-mvc sockjs spring-messaging stompjs


    【解决方案1】:

    使用ApplicationListener 中的模板发送消息应该可以工作。请查看此Spring WebSocket Chat 示例以获取示例。

    【讨论】:

    • 是的,我知道,我实际上遵循了您的示例,但我的订阅没有捕获通过 ApplicationListener 发送的消息。
    【解决方案2】:

    好的!尽管它可能很奇怪,但我的 Listener 在以下包中:

    package my.company.listener;

    但由于我在应用上下文中的配置,convertAndSend() 方法不起作用。

    @ComponentScan(basePackages = { "my.company" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = { "my.company.web.*" }))

    但是,当我将侦听器(使用 @Component 注释)移动到 web 子包时,它起作用了!

    package my.company.web.listener;

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2013-10-14
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      相关资源
      最近更新 更多