在Ubuntu上设置Redis的过期策略,可以通过以下几种方式实现:
EXPIRE
命令你可以使用EXPIRE
命令为特定的键设置过期时间。例如:
redis-cli EXPIRE mykey 3600
这会将键mykey
的过期时间设置为3600秒(即1小时)。
SETEX
命令SETEX
命令可以在设置键值对的同时设置过期时间。例如:
redis-cli SETEX mykey 3600 "Hello, Redis!"
这会将键mykey
的值设置为"Hello, Redis!"
,并设置过期时间为3600秒。
你可以在Redis的配置文件redis.conf
中设置默认的过期时间。找到或添加以下配置项:
default-expire 3600
这会将所有新创建的键的默认过期时间设置为3600秒。
maxmemory-policy
和maxmemory
为了更好地管理内存,你可以设置maxmemory
和maxmemory-policy
。例如:
maxmemory 1gb
maxmemory-policy allkeys-lru
maxmemory 1gb
:设置Redis最多使用1GB的内存。maxmemory-policy allkeys-lru
:当内存达到上限时,使用LRU(最近最少使用)算法删除键。如果你需要更复杂的过期策略,可以使用Lua脚本来实现。例如:
EVAL "return redis.call('SET', KEYS[1], ARGV[1]) and redis.call('EXPIRE', KEYS[1], ARGV[2])" 1 mykey "Hello, Redis!" 3600
这会设置键mykey
的值为"Hello, Redis!"
,并设置过期时间为3600秒。
如果你使用的是Redis Sentinel或Redis Cluster,可以在配置文件中设置全局过期策略。例如,在Sentinel配置文件中:
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
这些配置项可以帮助你在主节点故障时快速进行故障转移。
通过以上几种方式,你可以在Ubuntu上灵活地设置Redis的过期策略。根据你的具体需求选择合适的方法。