redis之setex保存json字符串

阅读更多
redis之setex, 设置过期秒数,redis服务器自动清理过期key

setex k1 3000 "value1"
get k1
ttl k1

注意:
CONFIG SET protected-mode no
/sbin/service iptables stop

(1)配置参数
spring.redis.host=192.168.191.128
spring.redis.port=6379
spring.redis.password=1
spring.redis.timeout=1000
spring.redis.jedis.pool.min-idle=5
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=2000

(2)自动加载参数
@Component
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.password}")
private String password;

@Value("${spring.redis.jedis.pool.max-active}")
private int poolMaxTotal;
@Value("${spring.redis.jedis.pool.max-idle}")
private int poolMaxIdel;
@Value("${spring.redis.jedis.pool.max-wait}")
private int poolMaxWait;

@Bean
public JedisPoolConfig getGenericObjectPoolConfig(){
JedisPoolConfig config=new JedisPoolConfig();
config.setMaxTotal(poolMaxTotal);
config.setMaxIdle(poolMaxIdel);
config.setMaxWaitMillis(poolMaxWait);
config.setTestOnBorrow(true);
return config;
}

@Bean
public JedisPool getJedisPool(JedisPoolConfig config){
JedisPool pool=new JedisPool(host,port);
//new JedisPool(config,host,port,timeout,password);

return pool;
}

@Bean
public Jedis getJedis(){
return new Jedis(host,port);
}

}

(3)redis连接
/**
* 需要可以将任意的类型转化为string类型,并且可以根据字符串还原出对象
*
* get,set方法 调用时,key都是加上前缀后的key,并且可以设置过期时间。
*/
@Service
public class RedisService {
private int expiredTime = 5;
@Autowired
private JedisPool jedisPool;

public T get(String prefix,String key,Class clazz){
Jedis j=null;
try{
j=jedisPool.getResource();
return string2Key(j.get(prefix+key) , clazz);
}finally{
j.close();
}
}

public void set(String prefix,String key,T value){
Jedis j=null;
try{
j=jedisPool.getResource();
String v=key2String(value);
System.out.println("v="+v);
//j.set(prefix+key, v);
j.setex(prefix+key, expiredTime, v);
}finally{
j.close();
}
}

public String key2String(T key){
return JSON.toJSONString(key);
}

public T string2Key(String key, Class clazz){
return JSON.parseObject(key, clazz);
}
}

(4)redis缓存应用(使用setex,默认5秒,过期自动删除)
@Controller("user_controller")
@RequestMapping("/user")
public class UserController{

@Autowired
private RedisService redisService;

@RequestMapping("/")
public String list(Model model,HttpServletResponse response) {
UserPO user = new UserPO();
user.setUserId(100);
user.setUserName("zhangsan");

String key = user.getUserId().toString();
//默认5秒过期,redis服务器自动清理过期的key
redisService.set("user", key, user);

UserPO resUser = redisService.get("user", key, UserPO.class);
System.out.println("resUser: "+resUser.getUserName());
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resUser = redisService.get("user", key, UserPO.class);
System.out.println("resUser: "+resUser.getUserName());
return "index";
}
}

你可能感兴趣的:(redis)