Redis使用一例

22 篇文章 0 订阅
16 篇文章 0 订阅

使用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文档



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值