Rabbitmqpool
import pika
import threading
import random
import uuid
import json # 框架模块
from django.conf import settings """
Class:
Parameters:
Connectionsize:int类型,Rabbitmqpool池连接的最大数
Channelsize:int类型,Rabbitmqpool池Channel的最大数
return:None
""" # 单例保证唯一
class Rabbitmqpool:
# 定义类属性
__instance = None
__lock = threading.Lock() def __init__(self, Connectionsize, Channelsize):
self.maxConnectionsize = Connectionsize
self.maxChannelsize = Channelsize
self.nowConnectionsize = 0
self.nowChannelsize = 0
self.connectpool = {}
self.channelpool = {}
self.certdic = {} def __new__(cls, Connectionsize, Channelsize):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance """
function: 获取一个空闲Channel或者新建一个Channel
Parameters: return:
channel:channel
cname:连接名
""" def get_channel(self):
try:
self.__lock.acquire()
cname = ""
channel = None
# 在已存在键中查找空闲Channel
for connectionname in self.connectpool:
if len(self.channelpool[connectionname]) != 0:
# print("取出一个Channel -----------------", len(self.channelpool[connectionname]))
channel = self.channelpool[connectionname][-1]
cname = connectionname
self.channelpool[connectionname] = self.channelpool[connectionname][0:-1]
# print("取出一个Channel")
break
# 如果没有找到空闲Channel,canme为"",则新建一个Channel
if cname == "":
if self.nowChannelsize < self.maxChannelsize:
# 从连接池返回一个连接的名字
if len(self.connectpool) != 0:
cname = random.choice(list(self.connectpool))
# 根据名字拿到此连接,传入连接和Pool池创建Channel
CreateChannel(self.connectpool[cname], self)
# 得到一个新Channel
channel = self.channelpool[cname][-1]
self.channelpool[cname] = self.channelpool[cname][0:-1]
print("创建一个Channel")
# 如果没有连接,则新建连接与channel
else:
if len(self.certdic) != 0:
cert = random.choice(list(self.certdic))
cname = str(uuid.uuid4().int)
print("创建一个连接")
CreateConnection(str(self.certdic[cert]["rabbitmq_host"]),
str(self.certdic[cert]["rabbitmq_port"]),
str(self.certdic[cert]["rabbitmq_virtual_host"]),
str(self.certdic[cert]["rabbitmq_user"]),
str(self.certdic[cert]["rabbitmq_password"]), self, cname)
CreateChannel(self.connectpool[cname], self)
# 得到一个新Channel
channel = self.channelpool[cname][-1]
self.channelpool[cname] = self.channelpool[cname][0:-1]
print("创建一个Channel")
else:
print("无法创建Channel,无连接凭证,不能创建连接!")
else:
print("无法创建Channel,超过限制") finally:
self.__lock.release()
return channel, cname def create_channel(self):
try:
self.__lock.acquire()
if len(self.certdic) != 0:
cert = random.choice(list(self.certdic))
cname = str(uuid.uuid4().int)
print("创建一个连接")
CreateConnection(str(self.certdic[cert]["rabbitmq_host"]), str(self.certdic[cert]["rabbitmq_port"]),
str(self.certdic[cert]["rabbitmq_virtual_host"]),
str(self.certdic[cert]["rabbitmq_user"]),
str(self.certdic[cert]["rabbitmq_password"]), self, cname)
CreateChannel(self.connectpool[cname], self)
# 得到一个新Channel
channel = self.channelpool[cname][-1]
self.channelpool[cname] = self.channelpool[cname][0:-1]
print("创建一个Channel")
return channel, cname
else:
print("无法创建Channel,无连接凭证,不能创建连接!")
return None, ""
finally:
self.__lock.release() def return_channel(self, channel, connectionname):
try:
self.__lock.acquire()
# print('还回去 return_channel')
self.channelpool[connectionname].append(channel)
# print('还回去 return_channel------------', len(self.channelpool[connectionname]))
finally:
self.__lock.release() def closepool(self):
pass def delconnection(self, connectionname):
try:
self.__lock.acquire()
if connectionname in self.connectpool:
print('删除链接connectionname', connectionname)
del self.connectpool[connectionname] self.nowConnectionsize = self.nowConnectionsize - 1
self.nowChannelsize = self.nowChannelsize - len(self.channelpool[connectionname])
print('删除connectionname', self.nowChannelsize)
del self.channelpool[connectionname] finally:
self.__lock.release() def get_certtemplate(self):
return {"rabbitmq_host": "", "rabbitmq_port": 5672, "rabbitmq_virtual_host": "", "rabbitmq_user": "",
"rabbitmq_password": ""} def addcert(self, cert):
self.certdic[cert["rabbitmq_host"]] = cert # 连接可以自己创建
class CreateConnection:
def __init__(self, rabbitmq_host, rabbitmq_port, rabbitmq_virtual_host, rabbitmq_user, rabbitmq_password,
Rabbitmqpool, Connectionname=str(uuid.uuid4().int), heartbeat=6000):
if Rabbitmqpool.nowConnectionsize < Rabbitmqpool.maxConnectionsize:
if Connectionname not in Rabbitmqpool.connectpool:
self.rabbitmq_user = str(rabbitmq_user)
self.rabbitmq_password = str(rabbitmq_password)
self.rabbitmq_host = rabbitmq_host
self.rabbitmq_port = rabbitmq_port
self.rabbitmq_virtual_host = rabbitmq_virtual_host
self.connectionname = Connectionname
# print(self.rabbitmq_user, self.rabbitmq_password, self.rabbitmq_host, self.rabbitmq_port,
# self.rabbitmq_virtual_host, self.connectionname)
credentials = pika.PlainCredentials(rabbitmq_user, rabbitmq_password)
try:
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=rabbitmq_host,
port=rabbitmq_port,
virtual_host=rabbitmq_virtual_host,
heartbeat=heartbeat,
credentials=credentials))
Rabbitmqpool.connectpool[Connectionname] = self
Rabbitmqpool.nowConnectionsize += 1
if self.connectionname not in Rabbitmqpool.channelpool:
Rabbitmqpool.channelpool[self.connectionname] = []
print("创建连接:", Connectionname)
except Exception as e:
print("创建连接失败:", e)
else:
print("创建连接失败,此连接名已存在:", Connectionname)
else:
print("创建连接失败,连接池已满,无法创建连接池") def get_connection(self):
return self.connection class CreateChannel:
def __init__(self, Connection, Rabbitmqpool):
# print('创建 CreateChannel')
Rabbitmqpool.channelpool[Connection.connectionname].append(Connection.get_connection().channel())
Rabbitmqpool.nowChannelsize += 1 class RabbitMaClientPoll:
rabbitmq_host = settings.RABBIT_HOST
rabbitmq_port = 5672
rabbitmq_user = settings.RABBIT_USERNAME
rabbitmq_password = settings.RABBIT_PASSWORD
rabbitmq_virtual_host = "/"
credentials = pika.PlainCredentials(rabbitmq_user, rabbitmq_password)
Pool = Rabbitmqpool(50, 100)
cert = Pool.get_certtemplate()
cert['rabbitmq_host'] = rabbitmq_host
cert['rabbitmq_virtual_host'] = rabbitmq_virtual_host
cert['rabbitmq_user'] = rabbitmq_user
cert['rabbitmq_password'] = rabbitmq_password
cert['rabbitmq_port'] = rabbitmq_port
Pool.addcert(cert)
instance = None def __init__(self):
cname_list = []
for i in range(50):
c, cname = self.Pool.create_channel()
cname_list.append((c, cname))
for item in cname_list:
c, cname = item
self.Pool.return_channel(c, cname) def __new__(cls, *args, **kwargs):
if cls.instance:
return cls.instance
else:
return super().__new__(cls) def producer(self, data):
data = json.dumps(data) try:
c, cname = self.Pool.get_channel()
c.basic_publish(exchange='',
routing_key=settings.QUEUE_TOPIC,
body=data, ) self.Pool.return_channel(c, cname)
except Exception as e:
print("发送错误:", e) # 链接过期
self.Pool.delconnection(cname) # channel过期时,删除此链接和此链接下的所有channel
c, cname = self.Pool.create_channel() # 创建一个新的链接和channel
c.basic_publish(exchange='',
routing_key=settings.QUEUE_TOPIC,
body=data, )
self.Pool.return_channel(c, cname) RabbitMaClientPoll_obj = RabbitMaClientPoll()
Rabbitmqpool的更多相关文章
- RabbitMaClientPoll
import pika import threading import random import uuid import json # 框架模块 from django.conf import se ...
随机推荐
- 2021 年最值得推荐的 7 个 Angular 前端组件库 - DevUI
摘要:DevUI 是一款面向企业中后台产品的开源前端解决方案,它倡导沉浸.灵活.至简的设计价值观,提倡设计者为真实的需求服务,为多数人的设计,拒绝哗众取宠.取悦眼球的设计.如果你正在开发 ToB 的工 ...
- Redis 与 Python 交互
1. Python 库安装 2. 交互代码范例 3. Redis 操作封装 4. 应用范例:用户登录 1. Python 库安装 联网安装 pip install redis 使用源码安装 到中文官网 ...
- 858. Mirror Reflection
There is a special square room with mirrors on each of the four walls. Except for the southwest cor ...
- 病毒木马查杀实战第009篇:QQ盗号木马之手动查杀
前言 之前在<病毒木马查杀第002篇:熊猫烧香之手动查杀>中,我在不借助任何工具的情况下,基本实现了对于"熊猫烧香"病毒的查杀.但是毕竟"熊猫烧香" ...
- hdu 1814 字典序最小的2sat(暴力深搜)
题意: 题意就是最基础的2sat,关系只有矛盾关系,然后二选一,关键是这个题目是输出字典序最小的那组解. 思路: 输出字典序最小,用强连通那个实现不了(起码没看到有人实现),其实我 ...
- hdu3746 KMP的next数组应用,求项链首尾项链循环
题意: 给你一个项链,问你最少加多少个珠子能满足整个项链是一个循环的项链(首尾相连) 思路: KMP的简单应用只要了解next数组的意义就好说了,下面总结下 next在循环方面 ...
- hdu4411 经典费用里建图
题意: 给以一个无向图,0 - n,警察在0,他们有k个警队,要派一些警队去1--n个城市抓小偷, 问所有吧所有小偷全抓到然后在返回0的最小路径和是多少,当地i个城市被攻击的时候他会通知i ...
- POJ 2516 基础费用流
题意 有n个顾客,m个供应商,k种货物,给你顾客对于每种货物的要求个数,和供应商对于每种货物的现有量,以及供应每种货物的时候供应商和顾客之间的运输单价,问你满足所有顾客的前提下的最小运输费 ...
- 逆向 ctype.h 函数库 isalnum、iscntrl、islower、isxdigit、tolower 函数
0x01 isalnum 函数 函数原型:int isalnum(int c); 函数功能:检查所传的字符是否是字母和数字 动态链接库:ucrtbase.dll C\C++ 实现: #define _ ...
- Linux系统登录相关
whoami:查看当前用户 who:查看当前登录系统的所有用户 tty指的是主机的图形化界面的面板 pts/x指的是远程ssh连接的窗口 who -b:主机的上一次启动时间 w:显示已经登陆系统的用户 ...