gpt4 book ai didi

spring - 如何在 Spring Boot 应用程序中向 STOMP CREATED 消息添加自定义 header ?

转载 作者:行者123 更新时间:2023-12-03 22:43:17 25 4
gpt4 key购买 nike

我正在尝试将自定义 header 添加到客户端在第一次连接时收到的 STOMP 'CREATED' 消息。这是使用 STOMP JavaScript 连接到 WebSocket 的函数:

function connect() {
socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
stompClient.connect('', '', function(frame) {
whoami = frame.headers['user-name'];
console.log(frame);
stompClient.subscribe('/user/queue/messages', function(message) {
console.log("MESSAGE RECEIVED:");
console.log(message);

showMessage(JSON.parse(message.body));
});
stompClient.subscribe('/topic/active', function(activeMembers) {
showActive(activeMembers);
});
});
}

此函数将以下内容打印到浏览器的控制台:
body: ""
command: "CONNECTED"
headers: Object
heart-beat: "0,0"
user-name: "someuser"
version: "1.1"

我想添加自定义标题,所以输出必须如下所示:
body: ""
command: "CONNECTED"
headers: Object
heart-beat: "0,0"
user-name: "someuser"
version: "1.1"
custom-header: "foo"

我的 Spring Boot 应用程序中有以下 WebSocket 配置。
WebSocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue", "/topic");
config.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat", "/activeUsers")
.withSockJS()
.setInterceptors(customHttpSessionHandshakeInterceptor());
}

...

@Bean
public CustomHttpSessionHandshakeInterceptor
customHttpSessionHandshakeInterceptor() {
return new CustomHttpSessionHandshakeInterceptor();

}

}

我试图注册“HandshakeInterceptor”来设置自定义 header ,但它没有用。这是'CustomHttpSessionHandshakeInterceptor':

CustomHttpSessionHandshakeInterceptor.java
public class CustomHttpSessionHandshakeInterceptor implements 

HandshakeInterceptor {

@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {


ServletServerHttpRequest servletRequest =
(ServletServerHttpRequest) request;
attributes.put("custom-header", "foo");
}
return true;
}

public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Exception ex) { }
}

我在 https://dzone.com/articles/spring-boot-based-websocket 找到了这个代码片段
有人可以解释一下为什么这种方法不起作用吗?是否有另一种方法可以在 Spring Boot 应用程序的服务器端为 STOMP 'CREATED' 消息设置自定义 header ?
谢谢!

最佳答案

也许为时已晚,但迟到总比没有好......

服务器消息(例如 CONNECTED)是不可变的,这意味着它们不能被修改。

我要做的是注册一个客户端出站拦截器并通过覆盖 preSend(...) 方法捕获连接的消息,并使用我的自定义 header 构建一个新消息。

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel)
{
LOGGER.info("Outbound channel pre send ...");
final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message);
final StompCommand command = headerAccessor.getCommand();
if (!isNull(command)) {
switch (command) {
case CONNECTED:
final StompHeaderAccessor accessor = StompHeaderAccessor.create(headerAccessor.getCommand());
accessor.setSessionId(headerAccessor.getSessionId());
@SuppressWarnings("unchecked")
final MultiValueMap<String, String> nativeHeaders = (MultiValueMap<String, String>) headerAccessor.getHeader(StompHeaderAccessor.NATIVE_HEADERS);
accessor.addNativeHeaders(nativeHeaders);

// add custom headers
accessor.addNativeHeader("CUSTOM01", "CUSTOM01");

final Message<?> newMessage = MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
return newMessage;
default:
break;
}
}
return message;
}

@UPDATE:::

需要的接口(interface)叫做 ChannelInterceptor要注册您自己的实现,您需要添加 @Configuration注释类
@Configuration
public class CustomMessageBrokerConfig extends WebSocketMessageBrokerConfigurationSupport
implements WebSocketMessageBrokerConfigurer{}

并覆盖一个方法 configureClientOutboundChannel 如下
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
log.info("Configure client outbound channel started ...");
registration.interceptors(new CustomOutboundChannelInterceptor());
log.info("Configure client outbound channel completed ...");
}

关于spring - 如何在 Spring Boot 应用程序中向 STOMP CREATED 消息添加自定义 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42166472/

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