Hello World 是开始探索新编程语言的一种简单方法,并且几乎总是人们创建的第一个程序。如果您正在阅读本文,您可能 Redis 或 Python 的新手,并且想要学习。为了帮助您做到这一点,让我们构建一个“Hello Redis”程序。
Redis
Redis,它是 REmote DIctionary Server 的缩写,是一个 BSD 许可的内存数据结构存储,由 Salvatore Sanfilippo 于 2009 年发布。Redis 与其他 NoSQL 数据库的主要区别之一是 Redis 提供的数据结构。Redis 开发人员可以使用类似于大多数编程语言中集合操作的命令,利用 字符串、哈希、列表、集合 和 排序集合 等数据结构,而不是使用表抽象。Redis 具有 复制 功能、服务器端脚本语言 (Lua)、事务 以及不同的 磁盘持久化 模式。
除非您为另一个项目安装了 Redis,否则它很可能没有与您的操作系统发行版捆绑在一起。使用您的操作系统包管理器或第三方端口系统,您可以在 Linux 和 MacOS 系统上下载并安装 Redis。大多数软件包将安装一个基本的 Redis 配置,该配置启动并监听端口 6379,这是 Redis 的默认端口。
Python
Python 是一种由 Guido van Rossum 创建的解释型高级编程语言。它于 1991 年在 Python 软件基金会许可证 下发布。该基金会负责监督 Python 的开发,Guido 担任该项目的终身仁慈独裁者 (BDFL)。Python 的设计宗旨是平易近人,语法简单,并强调可读性。其显著特点是代码的缩进级别用于指示块结构。
大多数 Linux 发行版和 MacOS 默认安装了 Python,因此您很可能已经拥有合适的版本。当前版本是 Python 3,因此本文中的代码旨在在其下运行,但许多操作系统安装了 Python 2,我们的代码也可以在 Python 2.7 中工作。
您需要安装 redis-py
包才能连接到 Redis,您可以使用 pip
或 pip3
(Python 包管理器) 通过以下命令来完成此操作
pip3 install redis
如果您看到类似于 Requirement already satisfied: Redis
的消息,则表示 Redis-py
包已安装在您的系统上。
Hello Redis
我们的 Hello Redis 程序将“hello”消息上传到 Redis 服务器,下载刚刚上传的消息,并将其显示给用户。用 Python (像大多数语言一样) 编写此程序需要五个基本步骤
- 导入 Redis 库
- 定义连接参数
- 实例化 Redis 连接对象
- 使用连接对象将消息上传到 Redis
- 使用连接对象从 Redis 下载消息
每个步骤都在下面的脚本中实现
#!/usr/bin/env python3
# step 1: import the redis-py client package
import redis
# step 2: define our connection information for Redis
# Replaces with your configuration information
redis_host = "localhost"
redis_port = 6379
redis_password = ""
def hello_redis():
"""Example Hello Redis Program"""
# step 3: create the Redis Connection object
try:
# The decode_repsonses flag here directs the client to convert the responses from Redis into Python strings
# using the default encoding utf-8. This is client specific.
r = redis.StrictRedis(host=redis_host, port=redis_port, password=redis_password, decode_responses=True)
# step 4: Set the hello message in Redis
r.set("msg:hello", "Hello Redis!!!")
# step 5: Retrieve the hello message from Redis
msg = r.get("msg:hello")
print(msg)
except Exception as e:
print(e)
if __name__ == '__main__':
hello_redis()
将代码复制到文件并将步骤 2 中的连接参数更改为连接到您自己的 Redis 实例后,您可以直接从 Unix shell 运行此脚本。如果您的连接参数指定正确,您将看到消息 Hello Redis!!!
。
一旦您熟悉了这段代码,请修改它以使用 set
和 get
方法上传不同的数据。从那里,您可以尝试上面链接的其他 Redis 数据类型。
1 条评论