封装redis异步类
sys_redis_helper.py
import redis
import json
import etc.config
from concurrent import futures
executor = futures.ThreadPoolExecutor(max_workers=1)
class RedisHelper(object):
def __init__(self):
self._pool_cache = redis.ConnectionPool(host=etc.config.redis_host, port=etc.config.redis_port,password=etc.config.redis_password,decode_responses=True)
def _publish(self, _channel, sendMsg):
_redisConn = redis.StrictRedis(connection_pool=self._pool_cache)
_redisConn.publish(_channel, json.dumps(sendMsg))
def _listen(self, pool_cache, _callBack, _callBackParam, _channel):
try:
_redisConn = redis.StrictRedis(connection_pool=pool_cache)
_pubsub = _redisConn.pubsub()
_pubsub.subscribe(_channel)
for item in _pubsub.listen():
if item['type'] == 'message':
_callBack(item["data"], _callBackParam)
except Exception as e:
print("-----RedisHelper--_listen ERROR--------", e)
def async_listen(self, _callBack, _callBackParam, _channel):
executor.submit(self._listen, self._pool_cache, _callBack, _callBackParam, _channel)
在主程序启动的地方添加监听
sys_redis_helper.RedisHelper().async_listen(sys_message_dispatch.message_dispatch, msg_url, "task_notify_channel")
完整的代码粘贴如下:
#! /usr/bin/python
# -*- coding:utf-8 -*-
import os
import tornado.httpserver
from tornado import ioloop
from tornado.options import define,options
import threading
import sys_redis_helper
import sys_message_dispatch
importlib.reload(sys)
define("port",default=int(etc.config.MAIN_SERVER_PORT),help="run on the given port",type = int)
'''use real local ip'''
define("ip",default=etc.config.MAIN_SERVER_PORT,help="run on the given ip",type = str)
define("debug",default=True,help="Debug Mode",type=bool)
define("index",default=0,help="Server Index",type=int)
if __name__=="__main__":
appObj = run_app.run_app_handle()
if "status" in appObj and appObj["status"] == 1:
app = appObj["app"]
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(app, max_buffer_size=9999999999, max_body_size=9999999999)
port = options.port + options.index
http_server.bind(port)
http_server.start(1)
# 启动成功
msg_url = "http://127.0.0.1:" + str(port) + "/" + "socket_api"
sys_redis_helper.RedisHelper().async_listen(sys_message_dispatch.message_dispatch, msg_url, "task_notify_channel")
ioloop.IOLoop.instance().start()
发布消息
sys_redis_helper.RedisHelper()._publish("task_notify_channel", _sendMsg)