gpt4 book ai didi

java - @MessageMapping 返回上的 STOMP header

转载 作者:行者123 更新时间:2023-12-01 17:55:11 24 4
gpt4 key购买 nike

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

@Controller
public class ChannelController {

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

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

当从客户端的 STOMP SEND 触发 receive 时,我希望带有书体的 STOMP MESSAGE 回复框架具有自定义 header : 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 header ?

最佳答案

如果返回值签名不重要,您可以使用 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 帧。

关于java - @MessageMapping 返回上的 STOMP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45613533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com