MemcacheQ安装与使用(二)

使用memcacheq做异步队列,做个简单的生产者-消费者模型。生产者将数据写入mq中,消费者异步去队列中去取数据,进而进一步的消费处理数据。


Python


#!/usr/bin/env python
#-*- coding:utf8 -*-

import sys
import time
import random

import memcache

mc = memcache.Client(["%s:%s"%("127.0.0.1", "22202")])
queue_name = "q1"
def putter():
    count = 0
    while True:
        data = "hello%d"%(count)
        mc.set(queue_name, data)
        print "put ", data
        count += 1
        time.sleep(random.randint(1, 10))

def process_data(data):
    print "processing data :", data

def getter():
    while True:
        data = mc.get(queue_name)
        if data:
            process_data(data)
        else:
            print "no message, sleep for a while ..."
            time.sleep(30)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Wrong arg numbers"
    else:
        cmd = sys.argv[1]
        if cmd == "put": putter()
        elif cmd == "get": getter()
        else: print "wrong cmd"

在使用时,开两个终端模拟两个进程,在一个终端中运行

python mqdemo.py put 

来模拟生产者;另一个终端中运行

 python mqdemo.py get 

模拟消费者。

1 comment:

Leave a Reply

Your email address will not be published. Required fields are marked *