前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Redis实现类似同步方法调用的功能(二)

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

作者头像
kongxx
发布2018-05-14 12:08:06
7670
发布2018-05-14 12:08:06
举报

接上一篇,这么干纯粹是为了好玩。

上一篇的博客中的例子只能处理一个Server对一个Client的情况,今天修改了一版,可以支持一个Server对多个Client。实现方式就是Server每派发一个动作就扔到一个线程里去,Client也类似每收到一个数据,就起一个线程去做自己的逻辑。这样看起来就有点像socket变成了。

代码语言:javascript
复制
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()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.08.19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档