@staticmethod无法正常工作。静态方法只能执行一个。但是,为了进行测试,我并行进行了3次调用,而静态方法被调用了3次。以下是代码和输出:
代码:
class KafkaReceiver:
_kafka_consumer = None
def __init__(self, topic):
KafkaReceiver._kafka_consumer = self.create_only_one_consumer()
@staticmethod
def create_only_one_consumer():
if KafkaReceiver._kafka_consumer is None:
KafkaReceiver._kafka_consumer = KafkaConsumer(KafkaReceiver._topic)
print("Consumer Created......")
return KafkaReceiver._kafka_consumer
输出:
Consumer Created......
Consumer Created......
Consumer Created......
并行呼叫代码:
r1 = grequests.get('http://localhost:5014/message/?message=hello', callback=do_something)#, hooks = {'response' : do_something})
r2 = grequests.get('http://localhost:5014/message/?message=helloworld', callback=do_something)#, hooks = {'response' : do_something})
r3 = grequests.get('http://localhost:5014/message/?message=hellothere', callback=do_something)#, hooks = {'response' : do_something})
grequests.map([r1, r2, r3])
预期结果: 对于django Web服务的每次调用,django都会创建(我认为)一个新线程。但是,此处的类不应创建使用者的实例。是锁问题(我尝试过使用锁和RLock,但它不适用于django)
在进一步的django调用中,第二个奇怪的事情是此静态方法未执行。