结论:Redis自动启动配置:在Linux下编辑/etc/systemd/system/redis.service文件,设置[Unit]、[Service]、[Install]部分,然后systemctl enable redis;持久运行用daemonize yes或systemd服务;服务稳定高效确保:开启AOF/RDB持久化、调整maxmemory、设置合理超时、监控内存使用、定期重启避免内存碎片。
配置Redis开机自启
sudo vim /etc/systemd/system/redis.service
[Unit] Description=Redis In-Memory Data Store After=network.target
[Service] User=redis Group=redis ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf ExecStop=/usr/local/bin/redis-cli shutdown Restart=always
[Install] WantedBy=multi-user.target
然后执行:systemctl daemon-reload;systemctl enable redis;systemctl start redis。
Ubuntu下Redis自启动
apt install redis-server 然后 sudo systemctl enable redis-server sudo systemctl start redis-server 检查:systemctl status redis-server
CentOS Redis systemd服务
cat > /usr/lib/systemd/system/redis.service <<EOF [Unit] Description=Redis persistent key-value database After=network.target [Service] Restart=always ExecStart=/usr/local/redis/bin/redis-server /etc/redis/redis.conf --supervised systemd ExecStop=/usr/local/redis/bin/redis-cli shutdown User=redis Group=redis EOF systemctl daemon-reload systemctl enable redis.service systemctl start redis.service
Redis持久化配置
在redis.conf中:save 900 1 #900秒内至少1个key变化 save 300 10 save 60 10000 appendonly yes #开启AOF
daemonize yes #后台运行
确保Redis稳定运行
maxmemory 2gb #限制内存 maxmemory-policy allkeys-lru #内存满时策略 timeout 0 #不超时 tcp-keepalive 60 #保持连接
使用supervisor监控:supervisord.conf中配置redis程序,重启策略。
Redis高可用配置
sentinel模式:配置sentinel.conf,sentinel monitor mymaster 127.0.0.1 6379 2 sentinel down-after-milliseconds mymaster 5000
集群模式:redis-trib.rb create --replicas 1
内存优化和监控
定期执行:redis-cli memory purge 监控工具:redis-stat, prometheus+Grafana 设置notify-keyspace-events Ex #键空间事件通知
FAQ
Q: Redis服务怎么检查是否自启?
A: systemctl is-enabled redis
Q: 持久化AOF和RDB哪个好?
A: AOF更安全持久,RDB恢复快,用两者结合。
Q: Redis内存满了怎么办?
A: 设置maxmemory和eviction策略,监控info memory。
Q: Windows下Redis自启怎么弄?
A: 用nssm工具安装为Windows服务,nssm install Redis "C:\redis\redis-server.exe" redis.conf