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. 修改httpd端口

    修改httpd端口 默认httpd端口为80,现在改成800 修改两个地方: 1.修改配置文件httpd.conf listen 把80改成需要的端口 2.修改配置文件httpd-vhosts.con ...

  2. jQuery隐藏和显示从上往下的实现方法

    jquery 显示隐藏方法实现动画效果 方向 显示 隐藏 左上角到右下角 show() hide() 垂直向下 slideDown() slideUp() 水平与垂直两个方向 toggle() 垂直向 ...

  3. 在 windows 上安装 git 2.15

    下载 by win 下载地址:https://git-scm.com/download/win 如下图.选择对应的版本下载: 安装 by win 1.双击下载好的git安装包.弹出提示框.如下图: 2 ...

  4. EditPlus编译运行java文件

    ok ---------------两张图完成

  5. 2019牛客多校A All-one Matrices——单调栈

    题目 求非嵌套子矩阵的个数. 分析 单调栈的套路题(类似的有求最大子矩阵). 首先,按列预处理,每个位置化成连续1的个数. 例如,左边的图转成右边.                      然后枚举 ...

  6. 三十八. 分库分表概述 配置mycat

    1.搭建mycat 分片服务器   数据库主机 192.168.4.55 使用db1库存储数据 数据库主机 192.168.4.56 使用db2库存储数据 主机 192.168.4.54 运行myca ...

  7. 使用webuploader实现大文件上传分片上传

    本人在2010年时使用swfupload为核心进行文件的批量上传的解决方案.见文章:WEB版一次选择多个文件进行批量上传(swfupload)的解决方案. 本人在2013年时使用plupload为核心 ...

  8. 一个milller_rabin模板

    #include <iostream> #include <cstdlib> #include <stdio.h> #include <algorithm&g ...

  9. 怎么联系$zcy$呢?

    \(QQ:2939533969\) \(luogu:\)little_sun 窝经常以little_sun,little_sun0331,zcy05331的昵称混迹于各大网站 窝的CSDN blog ...

  10. CUDA线程

    建议先看看前言中关于存储器的介绍:点击打开链接 线程 首先介绍进程,进程是程序的一次执行,线程是进程内的一个相对独立的可执行的单元.若把进程称为任务的话,那么线程则是应用中的一个子任务的执行.举个简单 ...