@MessageMapping返回STOMP标头

问题描述 投票:0回答:2

在我使用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回复框架与书体有一个自定义标题: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 
}
^@

如何在@MessageMapping中为回复返回值设置STOMP标头?

java spring spring-boot stomp spring-websocket
2个回答
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帧。


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);
}
© www.soinside.com 2019 - 2024. All rights reserved.