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. spark-submit之使用pyspark

    在linux下,执行pyspark代码 —— 实测有效:但是并不是所有的包都能够成功,一些很复杂的包或者对C依赖很深的包例如 numpy, pandas, scipy等,无法通过本方法实现:对一些比较 ...

  2. Python使用jieba分词

    # -*- coding: utf-8 -*- # Spyder (python 3.7) import pandas as pd import jieba import jieba.analyse ...

  3. mr-robot靶机练习

    在业余时间进行的靶机练习,也是根据网上的大牛做下来的,重复造轮子吧,但是个人感觉还是即使是造轮子也是需要自己动手呀,毕竟每个人做的过程中遇到的问题是不一样的,这样既可以帮助别人也能锻炼自己.希望可以帮 ...

  4. jupyter notebook new Python3报错:Permission denied: Untitled.ipynb,修改workspace

    点击新建Python文件即弹出弹窗显示 Permission denied: Untitled.ipynb 看到Permission denied 尝试是权限问题进行解决,各种百度结果都是对文件进行权 ...

  5. 一款免费监控aix与Linux的软件--nmon

    性能介绍 nmon 工具可以为 AIX 和 Linux 性能专家提供监视和分析性能数据的功能,其中包括: CPU 使用率 内存使用情况 内核统计信息和运行队列信息 磁盘 I/O 速度.传输和读/写比率 ...

  6. 系统间HTTP调用代码封装

    痛点 最近接手一个老项目,这个项目几经转手,到我这里时,发现代码的可阅读性实在是很差,对于一个有点代码洁癖的我来说,阅读起来实在是很难受.其中一个痛点,现在就拉出来讲讲.该项目需要与另外一个项目进行业 ...

  7. Apache查看连接数和限制当前的连接数

    在wamp环境下查看apche连接数和限制当前的连接数 httpd_mpm.conf文件在你apache安装上当的\\conf\\extra中,还在就是在要apache httpd.conf中把#In ...

  8. [TypeScript] vs code TSLint常见错误解决方案

    TSLint是一个Typescrip{过滤}t验证工具,用于检测代码. TSLint: comment must start with a space (comment-format) 注释必须从一个 ...

  9. vue 单向数据流

  10. css3多列布局瀑布流加载样式

    看了一些网站的瀑布流加载,正好看到css3的多列属性,尝试着写了一个css做布局的瀑布流. 直接上代码: <!DOCTYPE html> <html lang="en&qu ...