linux下用mython语言写的简单zeromq push/pull模式操作mysql数据

上游:

import zmq
import random
import time

context = zmq.Context()

# Socket to send messages on
sender = context.socket(zmq.PUSH)
sender.bind("tcp://*:5557")

print "Press Enter when the workers are ready: "
_ = raw_input()
print "Sending tasks to workers..."

# The first message is "0" and signals start of batch
sender.send('0')

# Initialize random number generator
random.seed()

# Send 100 tasks
total_msec = 0
for task_nbr in range(100):
# Random workload from 1 to 100 msecs
    workload = random.randint(1, 100)
    total_msec += workload
    sender.send(str(workload))
        print str(workload)
print "Total expected cost: %s msec" % total_msec

工厂:

import sys
import time
import zmq

context = zmq.Context()

# Socket to receive messages on
receiver = context.socket(zmq.PULL)
receiver.connect("tcp://localhost:5557")

# Socket to send messages to
sender = context.socket(zmq.PUSH)
sender.connect("tcp://localhost:5558")

# Process tasks forever
while True:
    s = receiver.recv()
# Simple progress indicator for the viewer
    sys.stdout.write(s)
    sys.stdout.flush()

    #Do the work
    time.sleep(int(s)*0.001)

    # Send results to sink
    sender.send(s)

下游:

import sys
import time
import zmq
import MySQLdb

context = zmq.Context()

# Socket to receive messages on
receiver = context.socket(zmq.PULL)
receiver.bind("tcp://*:5558")

# Wait for start of batch
s = receiver.recv()

# Start our clock now
tstart = time.time()

conn=MySQLdb.connect(host='localhost',user='root',passwd='19881028',port=3306)
cur=conn.cursor()
cur.execute('create database if not exists pymqsql')
conn.select_db('pymqsql')
cur.execute('create table test(id int)')
# Process 100 confirmations
total_msec = 0
values=[]
for task_nbr in range(100):
    s = receiver.recv()
    #if task_nbr % 10 == 0:
    sys.stdout.write(s)
        values.append(s)
    #else:
        #sys.stdout.write(':')
cur.executemany('insert into test values(%s)',values)
conn.commit()
cur.close()
conn.close()
# Calculate and report duration of batch
tend = time.time()
print "Total elapsed time: %d msec" % ((tend-tstart)*1000)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值