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 的同步通信的更多相关文章

  1. Redis2.2.2源码学习——Server&Client链接的建立以及相关Event

    Redis中Server和User建立链接(图中的client是服务器端用于描述与客户端的链接相关的信息) Redis Server&Client链接的建立时相关Event的建立(图中的cli ...

  2. NetMQ(ZeroMQ)Client => Server => Client 模式的实现

    ØMQ (也拼写作ZeroMQ,0MQ或ZMQ)是一个为可伸缩的分布式或并发应用程序设计的高性能异步消息库.它提供一个消息队列, 但是与面向消息的中间件不同,ZeroMQ的运行不需要专门的消息代理(m ...

  3. 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 ...

  4. 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. ...

  5. 鏈接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] 解決 啟動 ...

  6. 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 解决: 如果没有配置环境,在安 ...

  7. Socket编程--基础(基本server/client实现)

    IPv4套接口地址结构 IPv4套接口地址结构通常也称为“网际套接字地址结构”,它以“sockaddr_in”命名,定义在头文件中 LINUX结构下的常用结构,一般创建套接字的时候都要将这个结构里面的 ...

  8. 用XMLRPC开服务进行server/client通信

    本文讲一下怎样用python的xmlrpc开服务,进行server/client的通信. 应用场景:1)需多client訪问应用程序给予应答情况--网页服务.  2)数据极大,希望载入一次.后面仅仅用 ...

  9. 基于I/O的Server/Client实现

    在前面的文章中讲了基于NIO实现的Server/Client.本文就讲讲基于同步堵塞式I/O实现的Server/Client好与前面的NIO中的Server/Client进行对照. 网络编程中须要解决 ...

随机推荐

  1. C++读取中文或英文文件空格分割

    // show file content - sbumpc() example #include <iostream> // std::cout, std::streambuf #incl ...

  2. 7月新的开始 - Axure学习06 - 母版的使用

    母版的使用 主导航.底部.在很多页面上都是一样的: 如果在每一个页面都写一次的化.话.是非常浪费时间的,为了方便.可以使用母版: 母版可以帮助我们将一些元素重复利用,既可以保证页面的统一性.还可以节省 ...

  3. Oracle数据库 — DDL:数据定义语言

    1.数据定义语言:用于定义数据库的结构,比如创建.修改或删除数据库对象: 包括: CREATE TABLE:创建数据库表:创建表的命名规则: 2.以字母开头:在 1–30 个字符之间:只能包含 A–Z ...

  4. 利用JS对象把值传到后台

    记得以前刚写asp.net 从前台往后台传值 都是var data=A,B,C,D,E; 循环添加用逗号隔开 后台还要被测试测出只输入,就错了 哈哈..后来用✈◆类似的符号隔开 不是长久之计... 现 ...

  5. BZOJ 3162 / Luogu P4895: 独钓寒江雪 树hash+DP

    题意 给出一棵无根树,求本质不同的独立集数模100000000710000000071000000007的值. n≤500000n\le 500000n≤500000 题解 如果是有根树就好做多了.然 ...

  6. 51nod 1488 帕斯卡小三角 斜率优化

    思路:斜率优化 提交:\(2\)次 错因:二分写挂 题解: 首先观察可知, 对于点\(f(X,Y)\),一定是由某个点\((1,p)\),先向下走,再向右下走. 并且有个显然的性质,若从\((1,p) ...

  7. sql的九个常用语句是什么

    一.基础1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql server--- 创建 备份数 ...

  8. yum -y install 问题解决

    1.错误如下: Last login: Thu Jul 26 09:04:14 2018 from 192.168.3.250[root@diagbot01 ~]# yum -y install do ...

  9. eclipse和scala整合,打包配置文件及打包步骤

    我写的是maven项目,pom文件为: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" ...

  10. Greenplum 调优--数据分布法则 - 分布列与分区的选择

    分布列选择黄金法则 由于Greenplum是一个分布式的数据库,数据是分散存储在各个数据节点的,所以需要告诉Greenplum数据应该如何分布. 短板效应 当用户请求QUERY时,Greenplum会 ...