通过Redis的list来实现 Server - Client 的同步通信
Redis实现类似同步方法调用的功能(一)
首先声明,这么干纯粹是为了好玩。
通常我们用Redis主要是为了存储一些数据,由于数据在内存里,所以查询更新很快。同时我们也可以利用 Pub/Sub 功能来实现消息发布/订阅。但是今天我们来说说怎么通过Redis的list来实现 Server - Client 的同步通信。
具体需求
Client 端运行后监听 Server 端派发的请求,然后执行一些操作,并将结果返回给 Server 端。
实现想法
- 利用 Redis 的 list 数据结构,使用阻塞 pop 的方式实现 Client 端等待派发命令和 Server 端等待返回结果。
- 首先Server端生成一个全局唯一的key,并将key和data一起push到我们指定的一个队列里,这里是“myqueue”。lpush之后,Server端就使用brpop等待从“key”队列返回结果,并设置超时时间为2秒。
- Client端启动后,使用brpop从指定的队列里获取派发的命令,一旦收到Server端派发的数据,Client就会获取key和data,然后做自己的一些处理,处理完成后,就往“key”队列里lpush执行结果。
- 最后,Server端会从“key”队列里使用brpop获取执行结果。
实现代码
import redis
import time
import json
import threading
host = 'localhost'
port = 6322
queue = 'myqueue'
class Server(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
pool = redis.BlockingConnectionPool(host=host, port=port, db='0')
conn = redis.Redis(connection_pool=pool)
idx = 0
while True:
idx = idx + 1
key = str(idx)
data = "request_" + key
request = {'id': key, 'data': data}
print 'Server: Send request: %s' % request
conn.lpush(queue, json.dumps(request))
response = conn.brpop(key, 2)
if response:
print 'Server: Receive response: %s' % response[1]
else:
print "Server: Timeout!!!"
time.sleep(1)
class Client(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
pool = redis.BlockingConnectionPool(host=host, port=port, db='0')
conn = redis.Redis(connection_pool=pool)
while True:
msg = conn.brpop(queue)[1]
print 'Client: Receive request: %s' % msg
time.sleep(0.1)
d = json.loads(msg)
key = d.get('id')
d['data'] = "response_" + key
print 'Client: Send response: %s' % d
conn.lpush(key, json.dumps(d))
conn.expire(key, 5)
server = Server()
server.start()
client = Client()
client.start()
Redis实现类似同步方法调用的功能(二)
接上一篇,这么干纯粹是为了好玩。
上一篇的博客中的例子只能处理一个Server对一个Client的情况,今天修改了一版,可以支持一个Server对多个Client。实现方式就是Server每派发一个动作就扔到一个线程里去,Client也类似每收到一个数据,就起一个线程去做自己的逻辑。这样看起来就有点像socket变成了。
import redis
import time
import json
import threading
host = 'localhost'
port = 6322
queue = 'myqueue'
class Server(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
pool = redis.BlockingConnectionPool(host=host, port=port, db='0')
conn = redis.Redis(connection_pool=pool)
idx = 0
while True:
idx = idx + 1
key = str(idx)
data = "request_" + key
threading.Thread(target=ServerHandler(conn, key, data).handle).start()
time.sleep(1)
class ServerHandler(object):
def __init__(self, conn, key, data):
self.conn = conn
self.key = key
self.data = data
def handle(self):
request = {'id': self.key, 'data': self.data}
print 'Server: Send request: %s' % request
self.conn.lpush(queue, json.dumps(request))
response = self.conn.brpop(self.key, 2)
if response:
print 'Server: Receive response: %s' % response[1]
else:
print "Server: Timeout!!!"
class Client(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
pool = redis.BlockingConnectionPool(host=host, port=port, db='0')
conn = redis.Redis(connection_pool=pool)
while True:
msg = conn.brpop(queue)[1]
threading.Thread(target=ClientHandler(conn, msg).handle).start()
class ClientHandler(object):
def __init__(self, conn, msg):
self.conn = conn
self.msg = msg
def handle(self):
print 'Client: Receive request: %s' % self.msg
time.sleep(0.1)
d = json.loads(self.msg)
key = d.get('id')
d['data'] = "response_" + key
print 'Client: Send response: %s' % d
self.conn.lpush(key, json.dumps(d))
self.conn.expire(key, 5)
server = Server()
server.start()
client = Client()
client.start()
通过Redis的list来实现 Server - Client 的同步通信的更多相关文章
- Redis2.2.2源码学习——Server&Client链接的建立以及相关Event
Redis中Server和User建立链接(图中的client是服务器端用于描述与客户端的链接相关的信息) Redis Server&Client链接的建立时相关Event的建立(图中的cli ...
- NetMQ(ZeroMQ)Client => Server => Client 模式的实现
ØMQ (也拼写作ZeroMQ,0MQ或ZMQ)是一个为可伸缩的分布式或并发应用程序设计的高性能异步消息库.它提供一个消息队列, 但是与面向消息的中间件不同,ZeroMQ的运行不需要专门的消息代理(m ...
- redis.clients.jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set
使用哨兵模式连接redis连接池时,遇到错误: Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR Client sen ...
- docker报Error response from daemon: client is newer than server (client API version: 1.24, server API version: 1.19)
docker version Client: Version: 17.05.0-ce API version: 1.24 (downgraded from 1.29) Go version: go1. ...
- 鏈接Redis報錯`AUTH` failed: ERR Client sent AUTH, but no password is set [tcp://127.0.0.1:6379]
問題 鏈接Redis報錯`AUTH` failed: ERR Client sent AUTH, but no password is set [tcp://127.0.0.1:6379] 解決 啟動 ...
- window下安装redis报错: creating server tcp listening socket 127.0.0.1:6379: bind No error
window下安装redis报错: creating server tcp listening socket 127.0.0.1:6379: bind No error 解决: 如果没有配置环境,在安 ...
- Socket编程--基础(基本server/client实现)
IPv4套接口地址结构 IPv4套接口地址结构通常也称为“网际套接字地址结构”,它以“sockaddr_in”命名,定义在头文件中 LINUX结构下的常用结构,一般创建套接字的时候都要将这个结构里面的 ...
- 用XMLRPC开服务进行server/client通信
本文讲一下怎样用python的xmlrpc开服务,进行server/client的通信. 应用场景:1)需多client訪问应用程序给予应答情况--网页服务. 2)数据极大,希望载入一次.后面仅仅用 ...
- 基于I/O的Server/Client实现
在前面的文章中讲了基于NIO实现的Server/Client.本文就讲讲基于同步堵塞式I/O实现的Server/Client好与前面的NIO中的Server/Client进行对照. 网络编程中须要解决 ...
随机推荐
- Ubuntu apt-get锁定问题
- python中redis
一.简介 二.redis的安装和使用 三.python操作readis之安装和支持存储类型 四.python操作redis值普通链接 五.python操作redis值连接池 六.操作之String操作 ...
- P2P system: Napster
Napster structure client machines之所以叫peers是因为对于server来说这些machines是平等对待的 当你upload一首歌曲如PennyLane.mp3时, ...
- Debian 9.x "stretch" 解决 /etc/rc.local 开机启动问题
由于某些软件并没有增加开启启动的服务,很多时候需要手工添加,一般我们都是推荐添加命令到 /etc/rc.local 文件,但是 Debian 9 默认不带 /etc/rc.local 文件,而 rc. ...
- 007_Python3 字符串
字符串是 Python 中最常用的数据类型.我们可以使用引号( ' 或 " )来创建字符串. 创建字符串很简单,只要为变量分配一个值即可. 例如: var1 = 'Hello World!' ...
- spring boot + mybaits 处理枚举类 enum
枚举: //实现层调用 orderMapper.getOrder(OrderStatus.DISCOUNT); sql打印: 实际sql: select * from order where orde ...
- jquery validate 表单验证插件 代码
/* 表单验证 */ var signupFormValidator = $("#signupForm").validate({ /* 自定义验证规则 */ rules : { o ...
- ros python 四元数 转 欧拉角
import sysimport math w = -0.99114048481x = -0.00530699081719y = 0.00178255140781z = -0.133612662554 ...
- python eval的用法
>>>x = >>> eval( '3 * x' ) >>> eval('pow(2,2)') >>> eval('2 + 2' ...
- Linux之jq
什么是jq?jq是Linux下面把文本字符串格式化成json格式的工具 系统环境:centos 7 一.安装 (1)yum安装 a.安装epel源 # wget http://dl.fedorapro ...