SimpMessagingTemplate.convertAndSend不起作用

问题描述

我正在尝试使用spring-starter-websocket向订阅用户发送消息,但是看起来convertAndSend根本不发送消息。 @SendTo有效。
我的配置

@Configuration
@EnableWebSocketMessagebroker
public class WebSocketConfig implements WebSocketMessagebrokerConfigurer {

private final HttpHandshakeInterceptor httpHandshakeInterceptor;

public WebSocketConfig(HttpHandshakeInterceptor httpHandshakeInterceptor) {
    this.httpHandshakeInterceptor = httpHandshakeInterceptor;
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS().setInterceptors(httpHandshakeInterceptor);
}

@Override
public void configureMessagebroker(MessagebrokerRegistry registry) {
    registry.enableSimplebroker("/notifications");
    registry.setApplicationDestinationPrefixes("/app");
}

控制器:

@Controller
public class NotificationController {

    private final NotificationService notificationService;
    private final SimpMessagingTemplate template;

    public NotificationController(NotificationService notificationService,SimpMessagingTemplate template) {
        this.notificationService = notificationService;
        this.template = template;
    }

    @MessageMapping("/echo")
    public void send(String text) {
        template.convertAndSend("/notifications",text);
    }
}

测试用例:

@Autowired
    NotificationService notificationService;

    @Test
    public void testSubscribe() throws ExecutionException,InterruptedException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization","Bearer " + token);
        StompSession stompSession = stompClient.connect(WEBSOCKET_URI,new WebSocketHttpHeaders(httpHeaders),new StompSessionHandlerAdapter(){}).get();

        stompSession.subscribe(WEBSOCKET_TOPIC,new DefaultStompFrameHandler());

        stompSession.send("/app/echo","Test".getBytes());
        Assert.assertEquals("Test",blockingQueue.poll(1,SECONDS));
    }

    class DefaultStompFrameHandler implements StompFrameHandler {
        @Override
        public Type getPayloadType(StompHeaders stompHeaders) {
            return byte[].class;
        }

        @Override
        public void handleFrame(StompHeaders stompHeaders,Object o) {
            blockingQueue.offer(new String((byte[]) o));
        }
    }

结果,我有空姐队列。 @SentTo工作完美。

UPD:convertAndSend有效,但只能从控制器使用。

P.S。对不起,我的英语,希望您理解问题:-)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)