Redis defaults to only support the expiration of simple keys, such as the SortedSet type, but also for the entire set of expired processing, does not support the expiration of a member of set;
In order to solve this problem, the following are done:
1. Store key and value information to Redis and put key in set to set key expiration time;
This key can support expiration processing and remove key and value after expiration, but the key in set still exists;
A, in the processing that needs to determine the expiration of the key, such as the Boolean ContainsKey (Object key), first in the set set to get the corresponding key;
The TTL can be used to determine whether it exists, if no description has expired, remove the key from set;
b, scheduled tasks, some conditions, can expire after also will not be used, so the need to regularly clean key,checkexpire ();
2. The code is as follows
Public BooleanContainsKey (Object key) {Final byte[] Keybytes =Computekey (key); return(Boolean) Template.execute (NewRediscallback<boolean>() { PublicBoolean Doinredis (redisconnection connection)throwsDataAccessException {waitforlock (connection); Set<byte[]> Keys =connection.zrange (setname,0,-1); Booleanisexist=false; for(byte[] item:keys) { if(Arrays.equals (Keybytes,item)) {Long remain=Connection.ttl (item); if(remain==-2) {Connection.zrem (SetName, item);//Remove from set;}Else{isexist=true; } Break; } } returnisexist; } }, true);} Public voidCheckexpire () {Template.execute (NewRediscallback<object>() { PublicObject Doinredis (redisconnection connection)throwsDataAccessException {waitforlock (connection); //Connection.multi ();Set<byte[]> Keys =connection.zrange (setname,0,-1); for(byte[] item:keys) {Long remain=Connection.ttl (item); if(remain==-2){ //Connection.del (item); //remove key from setConnection.zrem (SetName, item); } } //connection.exec (); return NULL; } }, true);}
Spring-redis SortedSet type member Expiration time processing