def _init_event_center(self): """ 初始化事件中心 """ if config.rabbitmq: logger.info('rabbitmq config:', config.rabbitmq, caller=self) from xxx.event.event_center import event_center event_center.initialize()
async def initRedisPool(host='127.0.0.1', port=6379, db=None, password=None): """ 初始化连接池 """ global REDIS_CONN_POOL address = 'redis://{host}:{port}'.format(host=host, port=port) REDIS_CONN_POOL = await aioredis.create_redis_pool(address, db=db, password=password, encoding='utf-8') logger.info('create redis pool success.')
def _add_event_handler(self, event, callback): """ 增加事件处理回调函数 * NOTE: {"exchange": {"event_name": [callback_function, ...]}} """ if event.EXCHANGE in self._event_handler: if event.NAME in self._event_handler[event.EXCHANGE]: self._event_handler[event.EXCHANGE][event.NAME].append( callback) else: self._event_handler[event.EXCHANGE][event.NAME] = [callback] else: self._event_handler[event.EXCHANGE] = {event.NAME: [callback]} logger.info('self._event_handler:', self._event_handler, caller=self)
async def _connect(self): """ 建立TCP连接 """ logger.debug('host:', self._host, 'port:', self._port, caller=self) if self._connected: return transport, protocol = await aioamqp.connect(host=self._host, port=self._port, login=self._username, password=self._password) channel = await protocol.channel() self.channel = channel self._connected = True logger.info('Rabbitmq initialize success!', caller=self)
def ticker(self): """ 启动心跳, 每秒执行一次 """ self._count += 1 if config.hb_msg_interval > 0: if self._count % config.hb_msg_interval == 0: logger.info('do server heartbeat, count:', self._count, caller=self) # if self._count % 1 == 0: # logger.info('do server heartbeat, count:', self._count, caller=self) asyncio.get_event_loop().call_later(self._interval, self.ticker) for task in self.tasks: func = task['func'] args = task['args'] kwargs = task['kwargs'] kwargs['heart_beat_count'] = self._count asyncio.get_event_loop().create_task(func(*args, **kwargs))
def _init_db_instance(self): """ 初始化数据库对象 """ logger.info('init db instance start >>>', caller=self) if config.mongodb: from xxx.db.mongo import initMongodb logger.info('mongodb config:', config.mongodb, caller=self) initMongodb(**config.mongodb) if config.redis: from xxx.db.redis import initRedisPool logger.info('redis config:', config.redis, caller=self) self.loop.run_until_complete(initRedisPool(**config.redis)) logger.info('init db instance done <<<', caller=self)
async def subscribe(self, event, callback, broadcast=True, bind_queue=True): """ 注册事件 @param event 事件 @param callback 回调函数 @param broadcast 交换机是否需要广播消息 @param bind_queue 此事件是否需要绑定队列接收消息 """ await self._lock.acquire() logger.info('EXCHANGE:', event.EXCHANGE, 'QUEUE:', event.QUEUE, 'NAME:', event.NAME, caller=self) await self._initialize(event, broadcast, bind_queue) self._add_event_handler(event, callback) self._lock.release()
def initMongodb(host='127.0.0.1', port=27017, username='', password='', dbname='admin'): """ 初始化mongodb连接 """ if username and password: uri = 'mongodb://{username}:{password}@{host}:{port}/{dbname}'.format( username=quote_plus(username), password=quote_plus(password), host=quote_plus(host), port=port, dbname=dbname) else: uri = "mongodb://{host}:{port}/{dbname}".format(host=host, port=port, dbname=dbname) mongo_client = motor.motor_asyncio.AsyncIOMotorClient(uri) global MONGO_CONN MONGO_CONN = mongo_client logger.info('create mongodb connection pool.')
async def do_comsume(): for queue in self._consume_queues: logger.info('queue:', queue, caller=self) await self.channel.basic_consume(self._on_consume_event_msg, queue_name=queue)
def start(self): """ 启动 """ logger.info('start io loop ...', caller=self) self.loop.run_forever()