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客户端的更多相关文章

  1. 测试平台系列(80) 封装Redis客户端

    大家好~我是米洛! 我正在从0到1打造一个开源的接口测试平台, 也在编写一套与之对应的完整教程,希望大家多多支持. 欢迎关注我的公众号测试开发坑货,获取最新文章教程! 回顾 上一节我们编写了Redis ...

  2. StackExchange.Redis客户端读写主从配置,以及哨兵配置。

    今天简单分享一下StackExchange.Redis客户端中配置主从分离以及哨兵的配置. 关于哨兵如果有不了解的朋友,可以看我之前的一篇分享,当然主从复制文章也可以找到.http://www.cnb ...

  3. c#实现redis客户端(一)

    最近项目使用中要改造redis客户端,看了下文档,总结分享一下. 阅读目录: 协议规范 基础通信 状态命令 set.get命令 管道.事务 总结 协议规范 redis允许客户端以TCP方式连接,默认6 ...

  4. 使用StackExchange.Redis客户端进行Redis访问出现的Timeout异常排查

    问题产生 这两天业务系统在redis的使用过程中,当并行客户端数量达到200+之后,产生了大量timeout异常,典型的异常信息如下: Timeout performing HVALS Parser2 ...

  5. Redis客户端之Spring整合Jedis,ShardedJedisPool集群配置

    Jedis设计 Jedis作为推荐的java语言redis客户端,其抽象封装为三部分: 对象池设计:Pool,JedisPool,GenericObjectPool,BasePoolableObjec ...

  6. 从零开始写redis客户端(deerlet-redis-client)之路——第一个纠结很久的问题,restore引发的血案

    引言 正如之前的一篇博文,LZ最近正在从零开始写一个redis的客户端,主要目的是为了更加深入的了解redis,当然了,LZ也希望deerlet客户端有一天能有一席之地.在写的过程当中,LZ遇到了一个 ...

  7. Redis 客户端配置及示例

    一.redis自定义配置节点 <configSections> <section name ="RedisConfig" type="Amy.Toolk ...

  8. Redis客户端Java服务接口封装

    最近在学习Redis并集成到Spring中去,发现Spring的RedisTemplate并不好用,还没有MongoTemplate好用. 而且发现Jedis和ShardedJedis的方法非常多,覆 ...

  9. "Redis客户端连接数一直降不下来"的有关问题解决

    [线上问题] "Redis客户端连接数一直降不下来"的问题解决 前段时间,上线了新的 Redis缓存(Cache)服务,准备替换掉 Memcached. 为什么要将 Memcach ...

随机推荐

  1. 解决nginx [error] open() "usr/local/nginx/logs/nginx.pid" failed错误

    重新启动服务器,访问web服务发现无法浏览啦!登陆服务器之 后进到nginx使用./nginx -s reload重新读取配置文件,发现报nginx: [error] open() "/us ...

  2. Redis 实践1- redis介绍和安装

    redis是一个key-value存储系统,官方站点 http://redis.io   和memcached类似,但支持数据持久化 支持更多value类型,除了和string外,还支持hash.li ...

  3. [Uva10294]Arif in Dhaka

    [Uva10294]Arif in Dhaka 标签: 置换 Burnside引理 题目链接 题意 有很多个珠子穿成环形首饰,手镯可以翻转和旋转,项链只能旋转.(翻转过的手镯相同,而项链不同) 有n个 ...

  4. HashMap、Hashtable、 LinkedHashMap、TreeMap四者之分。

    java为数据结构中的映射定义了一个接口java.util.Map,此接口主要有四个常用的实现类,分别是HasMap.Hashtable.LinkedHasmap和TreeMap. (1)HashMa ...

  5. Java经典编程题50道之三

    打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身.例如:153是一个"水仙花数",因为153=1的三次 ...

  6. Ubuntu14.04上安装Composer

    1,查看机子上有没有安装php 2,下载Composer的安装包 3,安装Composer 4,设置Composer全局可访问

  7. 进入Docker容器

    在进入Docker容器之前,首先要运行对应的Docker容器,先使用命令docker ps查看正在运行的容器. docker inspect --format='{{.NetworkSettings. ...

  8. APP性能测试(电量)

    #encoding:utf-8 import csv import os import time #控制类 class Controller(object): def __init__(self, c ...

  9. 【重磅】PRO基础版免费,是时候和ExtJS说再见了!

    三石的新年礼物 9 年了,FineUI(开源版)终于迎来了她的继任者 - FineUIPro(基础版),并且完全免费!   FineUIPro(基础版)作为三石奉献给社区的一个礼物,绝对让你心动: 拥 ...

  10. Innotop简单介绍

      Innotop介绍 Innotop是一款Perl脚本编写.开源.功能强大的MySQ的监控工具,它通过文本模式(命令行模式)监控,功能强大,配置简单,易于使用等等特性.Innotop这个项目位于ht ...