使用Redis的一个更新缓存的方法,前提条件配置好了redis缓存服务器:
准备工作>>
redis.pool.maxActive=1024
redis.pool.maxIdle=200
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.ip=192.168.37.100
redis.port=6379
public class JedisPoolUtil {
private static JedisPool pool;
public static JedisPool getJedisPool() {
if (pool == null) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(Integer.valueOf(RedisConfig.JEDIS_MAX_ACTIVE));
config.setMaxIdle(Integer.valueOf(RedisConfig.JEDIS_MAX_IDLE));
config.setMaxWait(Long.valueOf(RedisConfig.JEDIS_MAX_WAIT));
config.setTestOnBorrow(Boolean.valueOf(RedisConfig.JEDIS_TEST_ON_BORROW));
config.setTestOnReturn(Boolean.valueOf(RedisConfig.JEDIS_TEST_ON_RETURN));
pool = new JedisPool(config, RedisConfig.JEDIS_IP, Integer.valueOf(RedisConfig.JEDIS_PORT));
}
return pool;
}
}
private Jedis jedis;
private JedisPool pool;
private Gson gson;
private StbDao stbDao;
public StbServiceImpl(){
this.pool = JedisPoolUtil.getJedisPool();
this.gson = new Gson();
}
public void setStbDao(StbDao stbDao) {
this.stbDao = stbDao;
}
更新Redis缓存服务器中的某个对象(Sorted Sets类型数据):
public void updateUserInfo(StbUser stb) {
// 更新缓存
try {
jedis = pool.getResource();
Set<String> ret = jedis.zrangeByScore(Constant.USR_INFO, stb.getCardId(), stb.getCardId());
StbUser stbUser = null;
if (ret != null && ret.size() > 0) {
String str = ret.iterator().next();
stbUser = this.gson.fromJson(str, StbUser.class);
}
Transaction t = jedis.multi();
//删除原有缓存中的数据
t.zrem(Constant.USR_INFO, this.gson.toJson(stbUser));
//添加新数据到缓存
t.zadd(Constant.USR_INFO, stb.getCardId(), this.gson.toJson(stb));
t.exec();
pool.returnResource(jedis);
} catch (Exception e) {
if (jedis != null) {
pool.returnBrokenResource(jedis);
}
throw new JedisException(e);
}
//更新数据库
stbDao.updateUserInfo(stb);
}
Gson是google的一个对象转JSON的开源工具 Gson API文档
Redis使用的一些方法可以参考Jedis API文档