在我使用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标头?
如果返回值签名不重要,您可以使用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帧。
你可以尝试这个解决方案:
@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);
}