redis安装 基于Ubuntu 22.04
本文演示如何在ubuntu22.04下,安装redis v6.0.16,并配置测试远程访问。
Step1 更新环境
bash
sudo apt update
Step2 安装redis
bash
sudo apt install redis-server -y
Step3 启动
sudo systemctl restart redis
sudo systemctl status redis
Step4 配置开机启动
bash
sudo systemctl enable --now redis-server
bash
redis-server -v
Step5 配置远程访问
vim
sudo vim /etc/redis/redis.conf
重启后,查看
bash
sudo ss -an | grep 6379
测试脚本
发布消息
python
import redis
# 创建连接
r = redis.Redis(host='localhost', port=6379, db=0)
# 设置和获取字符串
r.set('key', 'Hello, Redis!')
print(r.get('key').decode()) # 输出: Hello, Redis!
# 设置和获取哈希
r.hset('user:1000', 'name', 'Alice')
r.hset('user:1000', 'age', 30)
print(r.hget('user:1000', 'name').decode()) # 输出: Alice
print(r.hgetall('user:1000')) # 输出: {b'name': b'Alice', b'age': b'30'}
# 操作列表
r.lpush('mylist', 'item1')
r.lpush('mylist', 'item2')
print(r.lrange('mylist', 0, -1)) # 输出: [b'item2', b'item1']
# 操作集合
r.sadd('myset', 'member1')
r.sadd('myset', 'member2')
print(r.smembers('myset')) # 输出: {b'member1', b'member2'}
# 操作有序集合
r.zadd('mysortedset', {'one': 1, 'two': 2})
print(r.zrange('mysortedset', 0, -1, withscores=True)) # 输出: [(b'one', 1.0), (b'two', 2.0)]
# 使用事务
pipe = r.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.execute()
# 发布消息
r.publish('mychannel', 'Hello, Subscribers!')
订阅消息
python
import redis
# 创建连接
r = redis.Redis(host='localhost', port=6379, db=0)
def message_handler(message):
print("Received:", message['data'].decode())
pubsub = r.pubsub()
pubsub.subscribe(**{'mychannel': message_handler})
pubsub.run_in_thread(sleep_time=0.001)