使用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 ...
随机推荐
- Linux系统Go开发环境搭建
Go 语言是由谷歌的科学家开发的,并开源的新语言,被誉为"21世纪的C语言",它的主要目标是将静态语言的安全性和高效性与动态语言的易开发性进行有机结合,达到完美平衡,从而使编程变得 ...
- mongodb 配置均衡器的运行窗口
当系统的数据量增长不是太快的时候,考虑到数据迁移会降低系统性能,可以配置均衡器在只在特定时间段运行.详细的配置步骤如下: 连接到任意的mongos服务器,并通过安全认证(如果有认证的话). 切换到co ...
- ios音乐播放器demo
闲暇时间,写了一个音乐播放器. 个人认为,基于Demo 的学习是最有效果的. 想学习的同学,欢迎下载.知识,只有在传播的时候才有价值. 不懂之处,欢迎留言询问,将热情解答. 运行图 项目结构图 Git ...
- windows上nginx的安装和配置
http://www.cnblogs.com/Li-Cheng/p/4399149.html http://www.cnblogs.com/huayangmeng/archive/2011/06/15 ...
- 如何遍历 Windows 摄像头设备?
#include <stdlib.h> #include <iostream> #include <Windows.h> #include <comdef.h ...
- JDBC底层原理
Class.forName(“com.mysql.jdbc.Driver”)是 强制JVM将com.mysql.jdbc.Driver这个类加载入内存,并将其注册到DriverManager类,然后根 ...
- Navicat远程连接阿里云服务器的mysql
问题描述: 本机为win10,mysql安装在阿里云(Ubuntu系统)上,本机使用Navicat远程连接mysql,遇到一些坑,求助于阿里云,最终解决,特此记录一下! 安装mysql sudo ap ...
- 浏览器通过Scheme协议启动APP中的页面
在APP开发过程中,通过外部浏览器调起APP页面的场景也很普遍使用.下面就介绍一下通过外部H5页面唤起APP中页面的通用方法. 1.首先需要在AndroidMainifest.xml中对你要启动的那个 ...
- PHP解码unicode编码中文字符代码
function replace_unicode_escape_sequence($match) { return mb_convert_encoding(pack('H*', $match[1]), ...
- stm32开发之标准库的介绍
1 STM32标准外设库概述 STM32标准外设库之前的版本也称固件函数库或简称固件库,是一个固件函数包,它由程序.数据结构和宏组成,包括了微控制器所有外设的性能特征.该函数库还包括每一个外设的驱动描 ...