如何修改WebSocket配置中的主机URL以对接远程服务器
配置调整方案
你当前使用的<websocket:simple-broker>是Spring内置的内存级消息代理,仅支持同应用内的消息转发,无法对接独立远程WebSocket/STOMP服务器,需要按以下步骤调整配置:
1. 替换消息代理配置
将原有<websocket:simple-broker>节点替换为STOMP代理中继节点,完整调整后的配置如下:
<websocket:message-broker application-destination-prefix="/app"> <websocket:stomp-endpoint path="/stomp" allowed-origins="*"> <websocket:handshake-handler ref="myHandshakeHandler"/> <websocket:sockjs client-library-url="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"/> </websocket:stomp-endpoint> <!-- 替换原来的simple-broker为下面的stomp-broker-relay --> <websocket:stomp-broker-relay prefix="/topic,/queue" relay-host="remotemachineurl" relay-port="61614" system-login="远程broker管理员用户名" system-passcode="远程broker管理员密码" client-login="客户端连接用用户名" client-passcode="客户端连接用密码" use-tls="true"/> <websocket:client-inbound-channel> <websocket:interceptors> <ref bean="myInterceptor"/> </websocket:interceptors> </websocket:client-inbound-channel> </websocket:message-broker>
参数说明:
relay-host填写远程服务器域名remotemachineurlrelay-port填写远程STOMP服务端口61614- 因为你使用的是HTTPS/WSS协议,添加
use-tls="true"开启TLS适配 - 用户名密码按你远程broker的实际配置填写,无密码验证的话可以删除相关属性
2. 调整客户端连接地址
原本地测试时客户端连接地址为ws://localhost:${端口}/${应用上下文}/stomp,现在替换为对应远程地址即可:
- 如果Spring应用部署在本地,客户端直接连远程broker:
wss://remotemachineurl:61614/stomp - 如果Spring应用作为接入层部署在
remotemachineurl上:wss://remotemachineurl:${Spring应用端口}/${应用上下文}/stomp,消息会通过Spring的代理中继自动转发到本地61614端口的broker
3. 生产环境可选优化
- 建议将
allowed-origins="*"替换为你实际的客户端域名列表,降低跨域安全风险 - 如果远程broker使用自签TLS证书,需要在Spring应用和客户端的信任证书库中添加该自签证书
- 确认远程服务器61614端口的防火墙/安全组规则已放开,允许客户端机器的入站请求
内容的提问来源于stack exchange,提问作者Kaan Sercan Görür
相关产品推荐
相关产品推荐

