通过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进行对照. 网络编程中须要解决 ...
随机推荐
- 天兔 -Lepus 慢查询分析平台配置
想要实现慢查询查询分析,需要在被监控端安装percona-toolkit工具. 1.被监控端安装软件包 yum -y install perl-IO-Socket-SSL yum -y insta ...
- python函数式编程-匿名函数
>>> map(lambda x: x * x, [, , , , , , , , ]) [, , , , , , , , ] 关键字lambda表示匿名函数,冒号前面的x表示函数参 ...
- 用Python写网络爬虫 第二版
书籍介绍 书名:用 Python 写网络爬虫(第2版) 内容简介:本书包括网络爬虫的定义以及如何爬取网站,如何使用几种库从网页中抽取数据,如何通过缓存结果避免重复下载的问题,如何通过并行下载来加速数据 ...
- sql 索引的使用 转载:https://www.cnblogs.com/xiaoyangjia/p/11267191.html#mysql_performance
B-Tree索引的3个限制: 如果不是按照索引的最左列开始查找,则无法使用索引 不能跳过索引中的列.如果联合索引(a,b,c) ,如果使用条件a和c条件查询,那么只能使用索引的第一列a 如果查询中有某 ...
- nodeJs修改镜像源
// 设置 淘宝镜像源npm config set registry https://registry.npm.taobao.org // 查看 使用的 镜像源npm config get regis ...
- python中的lambda()函数
语句:print map(lambda x:x ** 2,[1,2,3,4,5]) 其中lambda()函数在Python文档,文档中解释如下: lambda An anonymous inline ...
- Solr添加paoding分词器
1.Solr3.6.2 并可运行 paoding-analysis3.0.jar 下载 2.1 解压{$Solr-Path}/example/webapp 下的solr.war文件,解压到当前文件夹 ...
- [USACO]骑马修栅栏 Riding the Fences
题目链接 题目简述:欧拉回路,字典序最小.没什么好说的. 解题思路:插入边的时候,使用multiset来保证遍历出出答案的字典序最小. 算法模板:for(枚举边) 删边(无向图删两次) 遍历到那个点 ...
- oracle的jdbc.properties文件配置
----------Oracle #do Oracle JDBC jdbc.driverClassName=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc:o ...
- leetcode解题报告(15):Third Maximum Number
描述 Given a non-empty array of integers, return the third maximum number in this array. If it does no ...