Redis实现类似同步方法调用的功能(一)

本文介绍如何利用Redis的List数据结构实现简单的Server-Client任务调度系统。客户端监听服务器端派发的任务,执行相应操作并返回结果。采用阻塞pop方式确保双方高效同步通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先声明,这么干纯粹是为了好玩。

通常我们用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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值