我正在尝试为WebSocket端点设置反向代理。WebSocket端点是在Spring Boot中编写的。暴露的端点使用Stomp over WebSocket协议
使用反向代理URL时未收到请求。直接从Angular应用中调用End Point就可以了。
尝试以下配置,但都不成功。
Apache2.4
# 1
<VirtualHost *:80>
ServerName example.com
ProxyPass "/TestWebApp/ws/" "ws://localhost:28081/TestWebApp/ws/"
ProxyPassReverse "/TestWebApp/ws/" "ws://localhost:28081/TestWebApp/ws/"
</VirtualHost>
或
# 2
<VirtualHost *:80>
ServerName example.com
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule (.*) ws://localhost:28081/TestWebApp/ws/ [P,L]
</VirtualHost>
Nginx1.21.6
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server 127.0.0.1:28081;
}
server {
listen 80;
server_name localhost;
set $url "127.0.0.1:28081";
location /TestWebApp/ws/ {
proxy_pass $url;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
}
}
}
浏览器控制台出现以下错误:
WebSocket连接到'ws://localhost/TestWebApp/ws/'失败:
在Angular客户端应用程序中使用的URL如下
ws://localhost/TestWebApp/ws/">
但是,如果使用直接URL(没有反向代理),则连接成功
直接URL ->ws://localhost: 28081/TestWebApp/ws/
在angular应用程序中使用以下代码
connect() {
//const socket = new WebSocket('ws://localhost:28081/TestWebApp/ws');
const socket = new WebSocket('ws://localhost/TestWebApp/ws/');
const stompClient = Stomp.over(socket);
stompClient.debug = null;
return stompClient;
}
ngAfterViewInit(): void {
let ws = this.connect();
ws.connect({}, (frame) => {
this.socketConnected = true;
alert("connected")
ws.subscribe('/errors', (message) => {
//this.toast.error(message.body);
this.socketConnected = false;
});
ws.subscribe('/user/algoJobQueue/jobStatus', (message) => {
console.log("got message");
});
})
}
我可以在Spring引导应用程序日志中看到请求没有从Apache2或Nginx流向Spring引导应用程序。因此,我怀疑存在配置错误。
在Apache 2或Nginx之外,任何一个配置修复对我来说都是可以的。我可以使用这两个服务器中的任何一个;
server {
listen 80;
server_name my.dmain.name;
access_log /var/log/nginx/dev_localhost.log;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}