@MessageMapping返回STOMP标头

时间:2017-08-10 12:18:06

标签: java spring spring-boot stomp spring-websocket

在我使用Spring Websocket的Spring Boot 1.5应用程序中,我想在@MessageMapping方法的返回值上设置自定义STOMP标头,但我不知道如何执行此操作。例如:

@Controller
public class ChannelController {

    @MessageMapping("/books/{id}")
    public Book receive(@DestinationVariable("id") Long bookId) {
        return findBook(bookId);
    }

    private Book findBook(Long bookId) {
        return //...
    }
}

从客户receive触发STOMP SEND后,我希望STOMP MESSAGE回复框与图书正文一起显示自定义标题:{{ 1}}像这样:

message-type:BOOK

如何在MESSAGE message-type:BOOK destination:/topic/books/1 content-type:application/json;charset=UTF-8 subscription:sub-0 message-id:0-7 content-length:1868 { "createdDate" : "2017-08-10T10:40:39.256", "lastModifiedDate" : "2017-08-10T10:42:57.976", "id" : 1, "name" : "The big book", "description" : null } ^@

中为回复返回值设置STOMP标头

2 个答案:

答案 0 :(得分:3)

如果返回值签名不重要,您可以使用SimpMessagingTemplate作为答案中注明的@Shchipunov:

@Controller
@AllArgsConstructor
public class ChannelController {

    private final SimpMessagingTemplate messagingTemplate; 

    @MessageMapping("/books/{id}")
    public void receive(@DestinationVariable("id") Long bookId, SimpMessageHeaderAccessor accessor ) {
        accessor.setHeader("message-type", "BOOK");

        messagingTemplate.convertAndSend(
            "/topic/books/" + bookId, findBook(bookId), accessor.toMap()
        );
    }

    private Book findBook(Long bookId) {
        return //...
    }
}

正确地序列化到问题中的MESSAGE帧。

答案 1 :(得分:0)

您可以尝试此解决方案:

@MessageMapping("/books/{id}")
public GenericMessage<Book> receive(@DestinationVariable("id") Long bookId) {
    Map<String, List<String>> nativeHeaders = new HashMap<>();
    nativeHeaders.put("message-type", Collections.singletonList("BOOK"));

    Map<String, Object> headers = new HashMap<>();
    headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, nativeHeaders);

    return new GenericMessage<Book>(findBook(bookId), headers);
}