清理redis缓存数据

import java.util.Timer;

import java.util.TimerTask;

 

import redis.clients.jedis.Jedis;

import redis.clients.jedis.Transaction;

 

 

public class Simple7 {

static int EXPIRED_SENCONDS = 60; //60秒过期,使用线程清除过期的数据

 

public static void main(String[] args) {

 

isServerRunning();

Jedis client = getConnection();

 

client.set("user:zhangsan", "1"); //user表

client.hset("time:user", "user:zhangsan", expiredDate()); // time表-记录键的过期时间

 

//周期性的删除过期数据(user表)

Timer timer = new Timer();

long delay = 1000;

long period = 30 * 1000;

TimerTask task = new ClearExpiredKeys(client);

timer.schedule(task, delay, period);

}

 

//redis事务

private static void transaction(Jedis client){

Transaction tr = client.multi();

tr.hset("user:www", "query", "1");

tr.exec();

}

 

//ping

private static void isServerRunning(){

String host = "127.0.0.1";

     Jedis jedis = new Jedis(host, 6379);

     System.out.println("Connection to server sucessfully");

     System.out.println("Server is running: "+jedis.ping());

}

 

static Jedis getConnection(){

String host = "127.0.0.1";

     Jedis client = new Jedis(host, 6379);

   return client;

}

 

static String expiredDate(){

Date d = new Date();

d.setSeconds(d.getSeconds() + EXPIRED_SENCONDS);

SimpleDateFormat f = new SimpleDateFormat("HHmmss");

return f.format(d);

}

 

 

}

 

 

class ClearExpiredKeys extends TimerTask{

private Jedis client;

 

public ClearExpiredKeys(Jedis client){

this.client = client;

}

 

@Override

public void run() {

 

Set fields = client.hkeys("time:user");

Iterator it = fields.iterator();

String field = null;

String expiredDate = null;

Date now = new Date();

SimpleDateFormat f = new SimpleDateFormat("HHmmss");

int inow = new Integer(f.format(now));

while(it.hasNext()){

field = it.next();

expiredDate = client.hget("time:user", field);

if(new Integer(expiredDate) < inow){

//client.del("user:zhangsan");

client.del(field);

client.hdel("time:user", field);

System.out.println("-- 删除键 " + field);

}

}

//client.close();

}

}

你可能感兴趣的:(java)