Reputation: 395
Sessions in my db are being set as a hash:
1) "sid:lpg3um654ckqp7tj7fkr2qs2Zz" (this has a ttl of a week)
2) "sid:lpg3um654ckqp7tj7fkr2qs2Yy" (this has a ttl of 6 days)
3) "sid:g6sftph5dnun5bk6l0hqyyh6p5" (this has a ttl of 5 days)
4) "sid:g6sftph5dnun5bk6l0hqyxh6x3" (this has a ttl of 4 days)
5) "sid:g6sftph5dnun5bk6l0hqyxh4t1" (this has a ttl of 3.5 days)
I know you can set a ttl on a single key from the command line, but how would you do that for a batch of keys that are going to expire in a certain period of time (i.e. less than 5 days ttl). Running said command should result in deleting entries 4 and 5.
Upvotes: 1
Views: 2888
Reputation: 49942
Here's a Lua script (must... honor... the... tag...) that uses DEL
to remove the sid:'s according to your definition (despite my comment re. KEYS
's use, since Lua scripts are atomic there's no need to SCAN
here and DEL
won't work anyway since SCAN
is random) and returns the names of deleted keys:
local exp=ARGV[1] * 60 * 60 * 24;
local exs={};
local keys=redis.call('keys', 'sid:*');
for _,v in next,keys,nil do
local ttl=redis.call('ttl', v);
if ttl < exp then
redis.call('del', v);
exs[#exs + 1] = v;
end
end
return exs;
Note: this script is anything by safe to use and could probably kill your production instance (not to mention it not being cluster safe) ;)
Upvotes: 1
Reputation: 395
#!/bin/bash
FIVEDAYS=432000
redis-cli KEYS "*" |
while read LINE;
do TTL=`redis-cli ttl $LINE `;
if [ $TTL -le $FIVEDAYS ];
then `redis-cli expire $LINE 5`;
echo "Deleted $LINE";
fi;
done;
Upvotes: 1