gpt4 book ai didi

spring-websocket - 添加 STOMP header 而不在 ChannelInterceptorAdapter 上重新创建消息

转载 作者:行者123 更新时间:2023-12-04 01:56:09 34 4
gpt4 key购买 nike

我需要向 STOMP 消息添加 header ,目前它的工作方式如下,但我正在重新创建消息,是否可以只添加 native header 而无需重新创建消息以提高性能。

public class MyChannelInterceptor extends ChannelInterceptorAdapter {


@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);

StompCommand command = accessor.getCommand();
if(command != null) {
log.debug("Receiving msg {} from {}",command,accessor.getUser().getName());
if(command == StompCommand.SEND) {
log.debug("Adding expires header to msg {} from {}",command,accessor.getUser().getName());
String ttlString = accessor.getFirstNativeHeader("ttl");
long ttl = 30000;
try {
ttl = Long.parseLong(ttlString);
}
catch(Exception ex) {
log.error("TTL header received but not in correct format {}",ttlString);
}
accessor.addNativeHeader("expires", Long.toString(System.currentTimeMillis() + ttl));

return MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders());
}
}
return message;
}

}

最佳答案

这就是我要找的

StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

上面的代码将获取消息的实际 StompHeaderAccessor,因此如果您操作 native header ,它们会直接反射(reflect)在消息上

StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);

将获得 header 的克隆,您必须使用新的克隆 header 创建新消息

下面是完整的固定代码

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {

StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
// StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
if(accessor != null) {
StompCommand command = accessor.getCommand();
if(command != null) {
log.debug("Receiving msg {} from {}",command,accessor.getUser().getName());
if(command == StompCommand.SEND) {

log.debug("Adding expires header to msg {} from {}",command,accessor.getUser().getName());
String ttlString = accessor.getFirstNativeHeader("ttl");
long ttl = 30000;
if(ttlString != null) {
try {
ttl = Long.parseLong(ttlString);
}
catch(Exception ex) {
log.error("TTL header received but not in correct format {}",ttlString);
}
}

accessor.addNativeHeader("expires", Long.toString(System.currentTimeMillis() + ttl));
// I don't need any more to create a new message
//return MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders());
}
}
}
return message;
}

关于spring-websocket - 添加 STOMP header 而不在 ChannelInterceptorAdapter 上重新创建消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085519/

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