关于websocket在⽣产环境中遇到的问题及解决办法
⼀⽣产环境说明
1) tornado 4.2
2) Tornado-MySQL
3) supervisor 3.0b2
4) protobuf 2.6.1
5) python 2.7.6
mysql下载add produce 6) nginx/1.4.6
⼆实际问题
1) 问:使⽤nginx 代理后不能访问报错 WARNING:tornado.access:400 GET /ws (127.0.0.1) 0.79ms
或者连接失败后会反复发起连接请求。
答:需要在nginx 的location中新增如下配置
# websocket
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
2) 问: a) The 'Access-Control-Allow-Origin' header contains multiple values '*, localhost', but only one is allowed.
Origin 'localhost' is therefore not allowed access.
b) websocket._exceptions.WebsocketBadStatusException: Handshake status 400
答:Access-Control-Allow-Origin是HTML5中定义的⼀种服务器端返回Response header,⽤来解决资源(⽐如字体)的跨域权限问题。它定义了该资源允许被哪个域引⽤,或者被所有域引⽤(google字体使⽤*表⽰字体资源允许被所有域引⽤)。
解决办法:只需要 add_header Access-Control-Allow-Origin ⼀次就好!
http {
......
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
......
}
3) 问:如何调试websocket?
答:可以通过 websocket-client 写脚本测试。具体实例可参看
$ sudo pip install websocket-client
$ python
Python 2.7.6
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits"or"license"for more information.
>>> import websocket
>>> websocket
<module 'websocket'from'/usr/local/lib/python2.7/dist-packages/websocket/__init__.pyc'>
4) 问:如何实现定时任务及stop server 前执⾏某个任务?
答:可以通过tornado.ioloop.PeriodicCallback执⾏定时任务
在supervisorctl stop/restart program_name 时捕获 signal.SIGINT signal.SIGTERM实现
import Queue
DIRTY_DATAS = Queue.Queue()
a)
from tornado.ioloop import PeriodicCallback
periodic = PeriodicCallback(lambda: sync_dirty_db_datas(DIRTY_DATAS), 5)
periodic.start()
b)
import signal
import tornado.ioloop
@utine
def signal_handler(signum, frame):
yield sync_dirty_db_datas(DIRTY_DATAS)
tornado.ioloop.IOLoop.instance().stop()
# receive SIGINT SIGTERM
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
5) 问:error: [Errno 24] Too many open files in python and tornado
[E 140102 17:07:37 ioloop:660] Exception in I/O handler for fd 11
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 653, in start
self._handlers[fd](fd, events)
File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 241, in wrapped
callback(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 136, in accept_handler
connection, address = sock.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
error: [Errno 24] Too many open files
答: update the field: open files.
6) 问:operationalerror (1040 'too many connections') in python and mysql
答:
mysql> show variables like "max_connections";
检查mysql可允许的最⼤连接数和⾃⾝的应⽤设置的最⼤可连接数,后者不可超过前者设置的最⼤值。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论