redis一篇入门

一、Redis 安装

Linux 系统安装

  1. 通过包管理器安装 (以 Ubuntu 为例):

    sudo apt update
    sudo apt install redis-server
    
  2. 从源码编译安装:

    wget https://download.redis.io/redis-stable.tar.gz
    tar -xzvf redis-stable.tar.gz
    cd redis-stable
    make
    sudo make install
    

Windows 安装

Windows 官方不支持 Redis,但可以使用:

  1. Microsoft 维护的 Windows 版本: https://github.com/microsoftarchive/redis
  2. 使用 WSL (Windows Subsystem for Linux)
  3. 使用 Docker 容器

二、Redis 配置

主要配置文件

Redis 配置文件通常位于 /etc/redis/redis.conf (Linux) 或安装目录中。

常用配置项

# 绑定IP地址,默认只允许本地访问
bind 127.0.0.1

# 端口号
port 6379

# 是否以守护进程运行
daemonize yes

# 数据持久化设置
save 900 1      # 900秒内有1次修改就保存
save 300 10     # 300秒内有10次修改就保存
save 60 10000   # 60秒内有10000次修改就保存

# 数据文件存储位置
dir /var/lib/redis

# 日志文件位置
logfile /var/log/redis/redis-server.log

# 设置密码
requirepass yourpassword

# 最大内存限制
maxmemory 100mb

# 内存满时的策略
maxmemory-policy allkeys-lru

配置生效

修改配置后需要重启 Redis 服务:

sudo systemctl restart redis-server  # 系统服务方式
或
redis-server /path/to/redis.conf     # 直接指定配置文件启动

三、Redis 基本使用

启动 Redis

redis-server          # 使用默认配置启动
redis-server /path/to/redis.conf  # 指定配置文件启动

连接 Redis

redis-cli             # 本地连接
redis-cli -h host -p port -a password  # 远程连接

基本命令示例

# 字符串操作
SET key value
GET key

# 哈希操作
HSET user:1000 name "John Doe" age 30
HGETALL user:1000

# 列表操作
LPUSH mylist a
RPUSH mylist b
LRANGE mylist 0 -1

# 集合操作
SADD myset a b c
SMEMBERS myset

# 有序集合操作
ZADD leaderboard 100 "player1" 200 "player2"
ZRANGE leaderboard 0 -1 WITHSCORES

# 键操作
KEYS *
DEL key
EXPIRE key 60  # 设置60秒过期
TTL key        # 查看剩余生存时间

持久化操作

SAVE          # 同步保存数据到磁盘
BGSAVE        # 异步保存数据到磁盘

四、Redis 高级特性

事务

MULTI
SET key1 value1
SET key2 value2
EXEC

发布/订阅

# 终端1: 订阅频道
SUBSCRIBE news

# 终端2: 发布消息
PUBLISH news "Hello World"

Lua 脚本

EVAL "return redis.call('GET', KEYS[1])" 1 mykey

五、Redis 管理

查看服务器信息

INFO        # 查看所有信息
INFO memory # 查看内存相关信息
INFO stats  # 查看统计信息

性能测试

redis-benchmark -n 100000 -c 100

安全建议

  1. 设置密码 (requirepass)
  2. 重命名或禁用危险命令 (如 FLUSHALL, CONFIG)
    rename-command FLUSHALL ""
    rename-command CONFIG "CONFIG-9b7d4e5f"
    
  3. 绑定特定IP,不要使用 0.0.0.0
  4. 使用防火墙限制访问

六、Redis 集群

主从复制

# 从服务器配置
replicaof 192.168.1.100 6379
masterauth yourpassword

Redis Cluster

  1. 创建集群:
    redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 \
    127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 \
    --cluster-replicas 1
    
  2. 连接集群:
    redis-cli -c -p 7000
    

七、常见问题解决

  1. 内存不足:

    • 设置 maxmemory 和 maxmemory-policy
    • 使用适当的数据类型减少内存占用
  2. 性能问题:

    • 避免使用 KEYS 命令,用 SCAN 代替
    • 使用管道(pipeline)减少网络往返
  3. 持久化问题:

    • 确保有足够的磁盘空间
    • 根据业务需求调整 save 配置

八、Redis 的主要特点

Redis 是一个高性能的内存键值数据库,支持多种数据结构,广泛应用于缓存、消息队列、实时分析等场景。以下是 Redis 的主要特点、使用场景以及性能指标数据:

  1. 高性能

    • 单实例 QPS(每秒查询数)可达 18万(腾讯云 Redis 8.0),读写延迟低于 100μs
    • 相比传统数据库,Redis 能处理 110,000 次读取/秒81,000 次写入/秒
  2. 支持多种数据结构

    • 字符串(String)、哈希(Hash)、列表(List)、集合(Set)、有序集合(Sorted Set)。
    • 高级数据结构:位图(Bitmap)、HyperLogLog(基数统计)、地理空间索引(Geo)、流(Stream)。
  3. 持久化机制

    • RDB(快照):定时保存数据到磁盘。
    • AOF(日志):记录所有写操作,保证数据安全。
  4. 高可用与分布式

    • 主从复制(Replication)实现数据备份。
    • Redis Sentinel 提供自动故障转移。
    • Redis Cluster 支持数据分片,适用于大规模数据存储。
  5. 原子性操作

    • 所有 Redis 操作都是原子性的,适合计数器、排行榜等场景。

九、Redis 的使用场景

  1. 缓存

    • 减轻数据库压力,提高响应速度(如电商商品详情缓存)。
    • 腾讯云 Redis 8.0 在电商热词统计场景下,延迟 <5ms,QPS >18万
  2. 会话存储(Session Storage)

    • 存储用户登录状态,支持分布式 Web 应用。
  3. 排行榜/计数器

    • 使用 Sorted Set 实现游戏排行榜、商品销量排行等。
  4. 消息队列

    • 利用 ListStream 实现异步任务处理(如订单队列)。
  5. 实时数据分析

    • 使用 HyperLogLog 统计 UV(独立访客),或 BitMap 记录用户签到。
  6. 分布式锁

    • 通过 SETNX 实现分布式环境下的资源互斥访问。
  7. 地理位置服务

    • 使用 Geo 数据结构存储经纬度,支持附近的人查询。
  8. AI 与向量搜索

    • Redis 8.2 支持 SVS-VAMANA 向量索引,适用于 AI 推理和高维数据检索。

十、Redis 性能指标对比

指标腾讯云 Redis 8.0阿里云 Redis 7.0华为云 GaussDB Cache
随机读延迟<100μs150μs180μs
单实例 QPS18万12万10万
主从故障恢复(RTO)<10秒30秒<30秒
冷数据存储成本0.024元/GB/月0.034元/GB/月-

十一、编程开发(1):使用 hiredis(官方 C 客户端)

安装 hiredis

sudo apt-get install libhiredis-dev  # Ubuntu
brew install hiredis                 # macOS

示例代码

#include <hiredis/hiredis.h>
#include <iostream>

int main() {
    // 1. 连接 Redis
    redisContext *c = redisConnect("127.0.0.1", 6379);
    if (c == nullptr || c->err) {
        if (c) {
            std::cerr << "Connection error: " << c->errstr << std::endl;
            redisFree(c);
        } else {
            std::cerr << "Can't allocate redis context" << std::endl;
        }
        return 1;
    }

    // 2. 执行 SET 命令
    redisReply *reply = (redisReply *)redisCommand(c, "SET foo bar");
    freeReplyObject(reply);

    // 3. 执行 GET 命令
    reply = (redisReply *)redisCommand(c, "GET foo");
    if (reply->type == REDIS_REPLY_STRING) {
        std::cout << "GET foo: " << reply->str << std::endl;
    }
    freeReplyObject(reply);

    // 4. 执行 HSET/HGET (哈希操作)
    redisCommand(c, "HSET user:1000 name John age 30");
    reply = (redisReply *)redisCommand(c, "HGET user:1000 name");
    std::cout << "HGET name: " << reply->str << std::endl;
    freeReplyObject(reply);

    // 5. 关闭连接
    redisFree(c);
    return 0;
}

编译运行

g++ -std=c++11 redis_demo.cpp -lhiredis -o redis_demo
./redis_demo

十二、编程开发(2):使用 redis-plus-plus(推荐,现代 C++ 封装)

安装 redis-plus-plus

git clone https://github.com/sewenew/redis-plus-plus.git
cd redis-plus-plus
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j
sudo make install

示例代码

#include <sw/redis++/redis++.h>
#include <iostream>

int main() {
    try {
        // 1. 创建 Redis 连接
        sw::redis::Redis redis("tcp://127.0.0.1:6379");

        // 2. 字符串操作
        redis.set("foo", "bar");
        auto val = redis.get("foo");
        if (val) {
            std::cout << "GET foo: " << *val << std::endl;
        }

        // 3. 哈希操作
        redis.hset("user:1000", { {"name", "John"}, {"age", "30"} });
        auto name = redis.hget("user:1000", "name");
        if (name) {
            std::cout << "HGET name: " << *name << std::endl;
        }

        // 4. 列表操作
        redis.rpush("mylist", {"a", "b", "c"});
        auto list = redis.lrange("mylist", 0, -1);
        for (const auto &item : list) {
            std::cout << "List item: " << item << std::endl;
        }

        // 5. 发布/订阅
        auto sub = redis.subscriber();
        sub.on_message([](std::string channel, std::string msg) {
            std::cout << "Received message: " << msg << " from channel: " << channel << std::endl;
        });
        sub.subscribe("news");
        sub.consume();  // 需要在另一个线程运行

    } catch (const sw::redis::Error &e) {
        std::cerr << "Redis error: " << e.what() << std::endl;
    }
    return 0;
}

编译运行

g++ -std=c++11 redis_plus_plus_demo.cpp -lredis++ -lhiredis -pthread -o redis_plus_plus_demo
./redis_plus_plus_demo

2个SDK功能对比

功能hiredisredis-plus-plus
易用性低(C 风格)高(C++ 封装)
线程安全
支持数据结构基础全量(STL 风格)
性能最高接近 hiredis
推荐场景极致性能需求一般 C++ 项目

常见问题

  1. 连接超时:检查 Redis 服务器是否运行 (redis-cli ping)。
  2. 内存泄漏hiredis 需手动释放 redisReply
  3. 线程安全hiredis 非线程安全,redis-plus-plus 是线程安全的。

推荐优先使用 redis-plus-plus,除非你需要极致的性能控制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抓饼先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值