Skip to content

Instantly share code, notes, and snippets.

@arjunprakash027
Last active September 22, 2023 18:41
Show Gist options
  • Save arjunprakash027/c7911630df2cb9348e83a6e9e7bca98e to your computer and use it in GitHub Desktop.
Save arjunprakash027/c7911630df2cb9348e83a6e9e7bca98e to your computer and use it in GitHub Desktop.
A python code to implement producer and consumer in async redis queue
import redis
import sys
import time
import json
import random
redis_conn = redis.Redis(host='localhost', port=6379)
def producer():
for i in range(20):
functions = ['add', 'sub', 'mul', 'div']
random_func = random.choice(functions)
ranEl1 = random.randint(1,100)
ranEl2 = random.randint(1,100)
message = {
'function':random_func,
'num1':ranEl1,
'num2':ranEl2,
}
message_json = json.dumps(message)
redis_conn.lpush('queue', message_json)
time.sleep(1)
print("message sent")
class perform:
def add(self, num1, num2):
return num1 + num2
def sub(self, num1, num2):
return num1 - num2
def mul(self, num1, num2):
return num1 * num2
def div(self, num1, num2):
return num1 / num2
def consumer():
p = perform()
functions_map = {
'add':p.add,
'sub':p.sub,
'mul':p.mul,
'div':p.div
}
while True:
message = redis_conn.rpop('queue')
if message is not None:
serialized_message = json.loads(message)
print(functions_map[serialized_message['function']](serialized_message['num1'],serialized_message['num2']))
if __name__ == '__main__':
if sys.argv[1] == 'producer':
producer()
else:
consumer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment