package com.zxl.redis.rediscode;
import redis.clients.jedis.Jedis;
import java.util.List;
public class LoginValidate {
final static int EXPIRE_TIME_MILLISECOND = 10*1000;
final static int MOST_TIMES_IN_TIME_LIMIT = 5;
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.0.3",6379);
jedis.select(0);
String userId="zxl";
loginValidateWithQueue(jedis,userId);
loginValidateWithQueue(jedis,userId);
loginValidateWithQueue(jedis,userId);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loginValidateWithQueue(jedis,userId);
loginValidateWithQueue(jedis,userId);
loginValidateWithQueue(jedis,userId);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loginValidateWithQueue(jedis,userId);
loginValidateWithQueue(jedis,userId);
List<String> values=jedis.lrange(userId,0,-1);
for (int i = 0; i < values.size(); i++) {
System.out.printf(values.get(i) + "\n");
}
jedis.del(userId);
jedis.close();
}
public static boolean loginValidateWithQueue(Jedis jedis, String userId) {
Long currentTime = System.currentTimeMillis();
if (jedis.llen(userId) < MOST_TIMES_IN_TIME_LIMIT) {
jedis.rpush(userId, currentTime.toString());
System.out.println(currentTime + " 登入成功!" + jedis.llen(userId));
return true;
} else {
String earliestTimeStr = jedis.lindex(userId, 0);
Long earliestTime = Long.valueOf(earliestTimeStr);
if (currentTime - earliestTime <= EXPIRE_TIME_MILLISECOND) {
System.out.println(EXPIRE_TIME_MILLISECOND/1000 + " 秒内只能操作" + MOST_TIMES_IN_TIME_LIMIT + " 次");
return false;
} else {
jedis.lpop(userId);
jedis.rpush(userId, currentTime.toString());
System.out.println(currentTime + " 登入成功!" + jedis.llen(userId));
return true;
}
}
}
}