A, redis expire command can be used to set a bond of survival time, time to redis automatically deleted after it.
- Set expire survival time (in / sec)
- pexpire provided survival time (/ msec)
- ttl / pttl the remaining lifetime of the review key
- persist cancel survival time
- expireat [key] unix timestamp 1351858600
- pexpireat [key] unix timestamp (in milliseconds) 1351858700000
Second, the application scenarios:
- Limited time promotions
- Website data cache (data for some of the need for regular updates)
- Restriction site visitors access frequency (for example: 1 minute access up to 10 times)
Third, the frequency of access restriction site visitors
package com.chb.common.iface.database.redis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
private final String host = "192.168.179.14";
private final int port = 6379;
public static void main(String[] args) {
RedisUtil redisUtil = new RedisUtil();
Jedis jedis = redisUtil.connect1();
for (int i = 0 ; i < 15; i++) {
boolean visited = redisUtil.checkLogin(jedis, "192.168.179.11");
System.out.println("是否允许访问:" + visited);
}
}
public boolean checkLogin(Jedis jedis, String key) {
String value = jedis.get(key);
if (value == null) {
jedis.set(key, "0");
jedis.expire(key, 60); // 设置生存周期60s
} else {
int count = Integer.parseInt(value);
if (count >= 10) {
System.out.println("当前访问频率过于频繁....");
return false;
}
}
jedis.incr(key); // 累加访问次数
return true;
}
public Jedis connect() {
Jedis jedis = new Jedis(host, port);
return jedis;
}
// 使用连接池
public Jedis connect1() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(100);//总连接数
poolConfig.setMaxIdle(10);//空闲链接数
poolConfig.setMaxWaitMillis(3000);//创建连接的超时时间
poolConfig.setTestOnBorrow(true);//在创建连接的时候是否会测试
JedisPool jedisPool = new JedisPool(poolConfig, host, port);
// 通过连接池获取jedis 连接
Jedis jedis = jedisPool.getResource();
return jedis;
}
}