nginx结合asgi部署聊天室
- 前言
- 演示地址
- asgi配置环境变量
- daphne运行asgi
- install supervisor
- nginx转发websokcet
- 结束
前言
大家好,我是yma16,本文分享nginx结合asgi部署聊天室
nginx是什么
Nginx是一款高性能的开源反向代理服务器,也可以作为负载均衡器、HTTP缓存、Web服务器和反向代理服务器。Nginx被广泛应用于各种场景,如高并发 Web 网站、大型的视频平台和互联网公司等。Nginx采用事件驱动、异步非阻塞的处理方式,在高并发场景下表现出色,能够有效地提升Web应用的性能和稳定性。
asgi是啥
ASGI是异步服务器网关接口(Asynchronous Server Gateway Interface)的缩写,它是Python中一种用于实现异步Web应用程序的接口规范。它允许Web应用程序与异步服务器(如Daphne、UVicorn等)进行通信,这种异步通信方式可以提高Web应用程序的性能和可扩展性。与传统的WSGI(Web Server Gateway Interface)相比,ASGI更加灵活和高效,适用于异步IO的场景。
演示地址
http://yongma16.xyz/#/onlinewebsocket
asgi配置环境变量
需要添加
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myblogsite.settings')
from django.core.asgi import get_asgi_application
# import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myblogsite.settings')
django_asgi_app = get_asgi_application()
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter,URLRouter#channels的路由
import webchat.routing
# django.setup()
application=ProtocolTypeRouter(
{
"http":get_asgi_application(),
#添加http协议
"websocket": AuthMiddlewareStack(
URLRouter(
webchat.routing.websocket_urlpatterns
#聊天app
)
),
#路由配置
}
)
daphne运行asgi
指定所有ip可以访问,开放8001端口
daphne -b 0.0.0.0 -p 8001 myproject.asgi:application
install supervisor
安装supervisor
yum install -y supervisor
生成配置文件
echo_supervisord_conf > /etc/supervisord.conf
编辑配置文件
[include]
files = supervisord.d/*.ini
表示配置文件读取supervisord.d目录下所有后缀为.ini的文件。
创建配置目录,并创建配置文件
mkdir /etc/supervisord.d/
vi /etc/supervisord.d/asgi.ini
编辑
[fcgi-program:asgi]
# TCP socket used by Nginx backend upstream
socket=tcp://localhost:8001
# Directory where your site's project files are located django项目路径
directory=/data/wwwroot/myblog_project/myblogsite
# Each process needs to have a separate socket file, so we use process_num
# Make sure to update "mysite.asgi" to match your project name 虚拟环境 相对路径下的asgi
command=/data/pyweb/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers myblogsite.asgi:application
# Number of processes to startup, roughly the number of CPUs you have
numprocs=4
# Give each process a unique name so they can be told apart
process_name=asgi%(process_num)d
# Automatically start and recover processes
autostart=true
autorestart=true
# Choose where you want your log to go
stdout_logfile=/data/asgilog/asgi.log
redirect_stderr=true
创建文件夹生成daphe的sock文件
$ sudo mkdir /run/daphne/
赋予权限
$ chmod +x /run/daphe
运行
$ supervisord -c /etc/supervisord.conf
ok! 没问题
查看日志
nginx转发websokcet
map
map $http_upgrade $connection_upgrade{
default upgrade;
'' close;
}
处理websocket的请求,发送的请求是:ws://yongma16.xyz/ws/webchat/DjangoVue/
代理配置
location /ws/{
proxy_pass http://127.0.0.1:8001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
发送请求成功!
部署成功!
redismanager查看连接成功!
结束
本文分享到这结束,如有错误或者不足之处欢迎指出,感谢大家的阅读!