python tornado 集成redis消息订阅的异步任务之后tornado主程序无法启动,解决方案

封装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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值