使用asyncio实现redis客户端
redis协议格式请参考,http://doc.redisfans.com/topic/protocol.html
这里简单介绍下:
*<参数数量> \r\n
$<参数 的字节数量> \r\n
<参数 的数据> \r\n
$<参数 N 的字节数量> \r\n
<参数 N 的数据> \r\n
发送给redis服务器时的数据要按照redis要求的协议格式发送,只有这样redis服务器才能成功解析。
首先根据协议格式写一个封包方法,代码如下:
def format_command(self, commands):
length = len(commands)
command = "*{}\r\n".format(length)
for v in commands:
bytes = v.encode("utf-8")
bytes_length = len(bytes)
sub_command = "${}\r\n".format(bytes_length) + "{}\r\n".format(v)
command += sub_command
return command
看到format_command函数中的“*”和“$”符号了么。其实就是根据commands列表中的数据然后按照redis协议格式封装起来的。
弄懂了如何安装redis协议封装数据之后,就可以把数据发送到redis服务器了。
asyncio的官方demo可参考:
https://docs.python.org/3/library/asyncio-stream.html#tcp-echo-client-using-streams
下面就是完整的代码,无其他依赖,顺利执行之后,可以通过redis-cli命令行查看是否设置成功。
class AsyncRedis:
def __init__(self, host, port, loop):
self.host = host
self.port = port
self.loop = loop
self.separator = "\r\n".encode()
async def connect(self):
reader, writer = await asyncio.open_connection(self.host, self.port, loop=self.loop)
self.reader = reader
self.writer = writer
def format_command(self, commands):
length = len(commands)
command = "*{}\r\n".format(length)
for v in commands:
bytes = v.encode("utf-8")
bytes_length = len(bytes)
sub_command = "${}\r\n".format(bytes_length) + "{}\r\n".format(v)
command += sub_command
print(command)
return command
def execute_command(self, command):
self.writer.write(command.encode("utf-8"))
async def set(self, key, value):
command = self.format_command(["SET", key, value])
self.execute_command(command)
ret, error = await self.wait_ret()
print(ret)
return ret
async def hset(self, hash_key, key, value):
command = self.format_command(["HSET", hash_key, key, value])
self.execute_command(command)
async def get(self, key):
command = self.format_command(['GET', key])
self.execute_command(command)
ret = await self.wait_ret()
return ret
async def wait_ret(self):
ret = await self.reader.readuntil(self.separator)
ret = ret.decode()
mark = ret[0:1]
if mark == "$":
pos = ret.index("\r\n")
ret = ret[1:pos]
ret = await self.reader.read(int(ret))
ret = ret.decode()
return ret, True
elif mark == "+":
pos = ret.index("\r\n")
ret = ret[1:pos]
return ret, True
elif mark == "-":
pos = ret.index("\r\n")
ret = ret[1:pos]
return ret, False
async def close(self):
self.writer.close()
import asyncio
async def NewRedis(loop):
redis = AsyncRedis("127.0.0.1", 6379, loop)
await redis.connect()
# await redis.get("name")
await redis.set("name", "云想衣裳花想容,春风拂槛露华浓。\r\n 若非群玉山头见,会向瑶台月下逢。")
loop = asyncio.get_event_loop()
loop.run_until_complete(NewRedis(loop))
loop.close()
使用asyncio实现redis客户端的更多相关文章
- 测试平台系列(80) 封装Redis客户端
大家好~我是米洛! 我正在从0到1打造一个开源的接口测试平台, 也在编写一套与之对应的完整教程,希望大家多多支持. 欢迎关注我的公众号测试开发坑货,获取最新文章教程! 回顾 上一节我们编写了Redis ...
- StackExchange.Redis客户端读写主从配置,以及哨兵配置。
今天简单分享一下StackExchange.Redis客户端中配置主从分离以及哨兵的配置. 关于哨兵如果有不了解的朋友,可以看我之前的一篇分享,当然主从复制文章也可以找到.http://www.cnb ...
- c#实现redis客户端(一)
最近项目使用中要改造redis客户端,看了下文档,总结分享一下. 阅读目录: 协议规范 基础通信 状态命令 set.get命令 管道.事务 总结 协议规范 redis允许客户端以TCP方式连接,默认6 ...
- 使用StackExchange.Redis客户端进行Redis访问出现的Timeout异常排查
问题产生 这两天业务系统在redis的使用过程中,当并行客户端数量达到200+之后,产生了大量timeout异常,典型的异常信息如下: Timeout performing HVALS Parser2 ...
- Redis客户端之Spring整合Jedis,ShardedJedisPool集群配置
Jedis设计 Jedis作为推荐的java语言redis客户端,其抽象封装为三部分: 对象池设计:Pool,JedisPool,GenericObjectPool,BasePoolableObjec ...
- 从零开始写redis客户端(deerlet-redis-client)之路——第一个纠结很久的问题,restore引发的血案
引言 正如之前的一篇博文,LZ最近正在从零开始写一个redis的客户端,主要目的是为了更加深入的了解redis,当然了,LZ也希望deerlet客户端有一天能有一席之地.在写的过程当中,LZ遇到了一个 ...
- Redis 客户端配置及示例
一.redis自定义配置节点 <configSections> <section name ="RedisConfig" type="Amy.Toolk ...
- Redis客户端Java服务接口封装
最近在学习Redis并集成到Spring中去,发现Spring的RedisTemplate并不好用,还没有MongoTemplate好用. 而且发现Jedis和ShardedJedis的方法非常多,覆 ...
- "Redis客户端连接数一直降不下来"的有关问题解决
[线上问题] "Redis客户端连接数一直降不下来"的问题解决 前段时间,上线了新的 Redis缓存(Cache)服务,准备替换掉 Memcached. 为什么要将 Memcach ...
随机推荐
- CentOS下安装XAMPP详细教程(转)
[原文]http://blog.csdn.net/hel12he/article/details/49781813 现在PHP的集成运行环境越来越多,个人比较喜欢XAMPP,更新速度快,好用,安装便捷 ...
- windows下apache服务器开启压缩和网页缓存
找到配置文件:http.conf apache开启压缩 一.开启配置,去除下面代码前面的#号LoadModule deflate_module modules/mod_deflate.soLoadMo ...
- SpringBoot 中常用注解
本篇博文将介绍几种SpringBoot 中常用注解 其中,各注解的作用为: @PathVaribale 获取url中的数据 @RequestParam 获取请求参数的值 @GetMapping 组合注 ...
- 1.8 range
哈哈,前边忘了介绍这个知识点了,老是用人家,不介绍一下都不好意思了. range()函数是一个用来创建数字序列的函数. 问题来了,为什么要写函数? 封装代码啊,让使用者不需要关心具体业务逻辑是如何实现 ...
- java遍历的优化
说明:这是在面试中面试官出的题.虽然是常见的优化问题,但这种经验的确很有用.感慨之余,分享出来,以此共勉. 场景:现有List<PersonA>,List<PersonB>,P ...
- Linux中文件夹的文件按照时间倒序或者升序排列
1.按照时间升序 命令:ls -lrt 详细解释: -l use a long listing format 以长列表方式显示(详细信息方式) -t sort by modification time ...
- MAC地址表配置与绑定
MAC地址表分类 ---静态MAC地址表项由用户手工配置,表项不老化: ---黑洞MAC地址表项包括源黑洞MAC地址表项和目的黑洞MAC地址表项,用于丢弃含有特定源MAC地址或目的MAC地址的报文(例 ...
- sqoop:mysql和Hbase/Hive/Hdfs之间相互导入数据
1.安装sqoop 请参考http://www.cnblogs.com/Richardzhu/p/3322635.html 增加了SQOOP_HOME相关环境变量:source ~/.bashrc ...
- ASP.NET 后台打开新页面
[TOC] Response.Write 这是最常见的后台打开新页面的方法. Response.Write("<script>window.open('~/FileView.as ...
- GridView 多余字符显示省略号,并在Tooltip中显示完整信息
效果 方法一:TemplateField 关键点 TemplateField的灵活性 CSS:overflow:hidden;text-overflow:ellipsis (溢出时隐藏;文本溢出时省略 ...