本地配置nginx websocket 是可以连接项目的,部署到线上,用的tomcat7,8 外置前端项目就不行
前端相关代码
后端
nginx配置
运行结果及报错内容
nginx日志
我的解答思路和尝试过的方法
我想要达到的结果
线上服务器连接成功
这个问题是因为你在开发时候用的websocket是被springboot提前创建出来的bean,而你部署到tomcat容器中后,它使用tomcat创建并管理的websocket,你的代码无法创建出bean。
这个问题也折腾过我很久,后来我实在不想跟它较劲了,就直接用了springboot的嵌入式tomcat来跑,不再把项目打包成war包给外部tomcat,问题也就避开了。
其实要解决创建bean的问题也是可以的,比较麻烦。
修改配置如下,重启nginx: nginx.exe -s reload
location /basic/ {
proxy_set_header Upgrade $http_upgrade; #这是webSocket的配置
proxy_set_header Connection "Upgrade"; #这是webSocket的配置
proxy_http_version 1.1; #这两个最好也设置
proxy_read_timeout 6000s;
proxy_pass http://127.0.0.1:8098/;
}
https://www.bianchengquan.com/article/608566.html
类似的问题提供个解决思路
因为tomcat下的websocket相关的jar与你项目打包的冲突
解决方法:
项目打包的时候排除websocket依赖的jar即可。
确定环境配置正确?
将 websocket api .jar 安装到应用程序的 WEB-INF/lib 目录中
请确保你已经为websocket api配置了"provided"的作用域,并且把websocket-api.jar、tomcat7-websocket.jar 复制到tomcat lib(/usr/share/tomcat7/lib/)目录下。
这个看上去还是nginx的问题,你可以把前端报错贴出来
1, 看下nginx 配置了哪些模块, 使用命名: ./nginx -V
2,看下有没有 --with-stream 这个模块,websocket必须要,如果没有 需要把这个模块从新编译到nginx ;
添加步骤你可以搜索 “ nginx 添加stream模块 ”
3, 添加后重新配置nginx
upstream websocket.service {
server xx.xxx.xxx:9090;
}
server {
listen 80;
server_name localhost;
location /iip/websocket {
proxy_read_timeout 3600;
proxy_pass http://websocket.service/;
proxy_headers_hash_bucket_size 128;
proxy_headers_hash_max_size 1024;
proxy_redirect default;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
4 ,前端 websoket地址修改成 http://localhost/iip/websocket/xxxx
打war包的时候把WebSocketConfig这个类注释掉,然后放到tomcat就可以了
项目的web.xml 有和tomcat8对应吗
经过nginx的话用http://xxxxxx:9090/websocket/xxxxxx访问不要加上iip,试一下
如下图,将路径中的符号/去掉试试,如果还是不行,同时将proxy-pass中路径最后一级的符号也去掉试试
nginx.conf中加入配置
location / {
...
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
...
}
1
2
3
4
5
6
./nginx -s reload重新加载使配置生效;
————————————————
版权声明:本文为CSDN博主「椰汁菠萝」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/suo082407128/article/details/111860353
websoket是基于tcp的,使用server中的代理是不行的,需要在upstream中配置
# 在http上下文中增加如下配置,确保Nginx能处理正常http请求。
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
#ip_hash;
server localhost:8010;
server localhost:8011;
}
# 以下配置是在server上下文中添加,location指用于websocket连接的path。
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/yourdomain.log;
location / {
proxy_pass http://websocket;
proxy_read_timeout 300s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
}
1、你本地websocket的端口为9090端口;
2、你本地websocket的访问路径为ip:port/iip/websocket,所以你nginx的配置需要更新为/iip/websocket/
nginx与Tomcat分开部署
项目结构发一下