async def connect(self): ''' 连接 RabbitMQ,并初始化exchanges :param reconnect: 若连接非初连接,进行重置操作 :return: ''' # 若已连接,则不进行连接操作 if self._connected: return logger_info.info('Host:%s,Port:%s - Try connecting RabbitMQ!' % (self._host, self._port)) try: transport, protocol = await aioamqp.connect( host=self._host, port=self._port, login=self._username, password=self._pwd, virtualhost=self._vhost) except aioamqp.AmqpClosedConnection as e: logger_error.error('Rabbit connection error:%s' % e) return finally: if self._connected: return self._protocol = protocol self._channel = await protocol.channel() self._connected = True await self._init_exchanges() logger_info.info("%s - RabbitMQ initialize success!" % self)
def ticker(self, app=None): """ 启动心跳, 每秒执行一次 """ self._count += 1 # 打印心跳次数 if self._print_interval > 0: if self._count % self._print_interval == 0: logger_info.info("Do server heartbeat, count:%s" % self._count) # 设置下一次心跳回调 asyncio.get_event_loop().call_later(self._interval, self.ticker, app) # 执行任务回调 for task_id, task in self._tasks.items(): interval = task["interval"] if self._count % interval != 0: continue func = task["func"] args = task["args"] kwargs = task["kwargs"] kwargs["task_id"] = task_id kwargs["heart_beat_count"] = self._count asyncio.get_event_loop().create_task(func(*args, **kwargs)) # 广播服务进程心跳 if self._broadcast_interval > 0: if self._count % self._broadcast_interval == 0: self.alive(app)
def get(self): mongo = self.settings['mongo'] res = yield mongo.do_find_one('testtable', {'name': 'name'}) logger_info.info(res) # print(res) r = yield mongo.do_find('testtable', limit=3) # print(r) self.write('ok')
def start_server(self): """ 启动服务 :return: """ http_server = httpserver.HTTPServer(self.app) http_server.listen(options.PORT) self.make_safely_shutdown(http_server, self.loop) logger_info.info('server start') self.loop.start()
async def _check_connection(self, task_id, *args, **kwargs): if self._connected and self._channel and self._channel.is_open: logger_info.info("%s - RabbitMQ connection ok." % self) return logger_error.error("%s - CONNECTION LOSE! START RECONNECT RIGHT NOW!" % self) self._connected = False self._protocol = None self._channel = None self._event_handler = {} asyncio.get_event_loop().create_task(self.connect())
async def subscribe(self, async_callback=None, queue_name='', *args, **kwargs): ''' 订阅指定队列 async_callback : must Asynchronous callback. :return: ''' await self._channel.basic_consume(async_callback, queue_name=queue_name, no_ack=True) logger_info.info('%s - Subscribe success! queue_name:%s' % (self, queue_name))
async def register(self, async_callback, queue_name, exchange_name, routing_key='', prefetch_count=1): data_dict = dict( async_callback=async_callback, queue_name=queue_name, exchange_name=exchange_name, routing_key=routing_key, prefetch_count=prefetch_count, ) self._subscribers.append(data_dict) logger_info.info('%s - Subscribers append success! queue_name:%s' % (self, queue_name))
async def producer(self, exchange_name='', exchange_type='', *args, **kwargs): ''' 生产者初始化exchange :return: ''' await self._channel.exchange_declare(exchange_name=exchange_name, type_name=exchange_type, durable=True, *args, **kwargs) logger_info.info('%s - Create exchange success! name:%s,type:%s' % (self, exchange_name, exchange_type))
async def beat_ping(self, *args, **kwargs): ''' 向所有用户推送ping dict,若没有 pong 返回则断开连接 - ping值默认为13位时间戳 - 推送数据手动 gzip 压缩 :return: None ''' logger_info.info('Beat-Ping is running.') data_dic = {'ping': self.ping} if self.bool_gizp: data = get_gzip(data_dic) else: data = data_dic for user in self.user_infos: user.write_message(data, binary=self.bool_gizp) self.user_infos[user]['ping'] = data_dic['ping'] if self.user_infos[user]['count'] == 2: user.close() self.user_infos.pop(user) else: self.user_infos[user]['count'] += 1
async def publish(self, msg, exchange_name='', routing_key='', *args, **kwargs): ''' 广播至指定的exchange :param msg: 接受dict,处理成json格式 :return: ''' if not self._connected: logger_error.error("RabbitMQ not ready right now!", caller=self) return json_msg = json.dumps(msg) await self._channel.basic_publish(payload=json_msg, exchange_name=exchange_name, routing_key=routing_key, *args, **kwargs) logger_info.info('%s - Publish messages success! name:%s' % (self, exchange_name))
async def consumer(self, queue_name='', exchange_name='', routing_key='', prefetch_count=1, *args, **kwargs): ''' e消费者初始化queue,绑定指定exchang :return: ''' try: await self._channel.queue_declare(queue_name=queue_name, auto_delete=True) except SynchronizationError as e: pass await self._channel.queue_bind(queue_name=queue_name, exchange_name=exchange_name, routing_key=routing_key) await self._channel.basic_qos(prefetch_count=prefetch_count) logger_info.info( '%s - Consumer initialize success! exchange_name=%s,queue_name:%s' % (self, exchange_name, queue_name))