`

Redis Java API编程

 
阅读更多

Redis 目前已经成为最流行的内存数据库之一,Java版本的API使用起来也非常方便;配合Spring-data 的项目可以很方便的使用redis的内存功能,将dao与redis整合。今天我们只介绍Redis的Java API, 借助jdk的序列化工具,我们可以将对象存存储到内存中;

 

package com.techstar.cache;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import com.techstar.jhop4.util.AssertUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.exceptions.JedisException;

/**
 * RedisZkConnection to operate the redis's data
 * @author mrh 2016-05-25
 *
 */
public class RedisUtils {
        private ShardedJedisPool shardedJedisPool;
	public RedisUtils(ShardedJedisPool shardedJedisPool) {
		this.shardedJedisPool
	}

	private static final Logger logger = Logger.getLogger(RedisUtils.class);
	
	/**
	 * 对象转成字节码
	 */
	@SuppressWarnings("rawtypes")
	private RedisSerializer keySerializer = new JdkSerializationRedisSerializer();
	@SuppressWarnings("rawtypes")
	private RedisSerializer valueSerializer = new JdkSerializationRedisSerializer();
	
	/**
	 * 设置一个key的过期时间(单位:秒)
	 * 
	 * @param key
	 *            key值
	 * @param seconds
	 *            多少秒后过期
	 * @return 1:设置了过期时间 0:没有设置过期时间/不能设置过期时间
	 */
	public long expire(String key, int seconds) {
		if (!AssertUtil.isVal(key)) {
			return 0;
		}
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.expire(key, seconds);
		} catch (Exception ex) {
			logger.error("EXPIRE error[key=" + key + " seconds=" + seconds + "]" + ex.getMessage(), ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		
		return 0;
	}

	/**
	 * 设置一个key在某个时间点过期
	 * 
	 * @param key
	 *            key值
	 * @param unixTimestamp
	 *            unix时间戳,从1970-01-01 00:00:00开始到现在的秒数
	 * @return 1:设置了过期时间 0:没有设置过期时间/不能设置过期时间
	 */
	public long expireAt(String key, int unixTimestamp) {
		if (!AssertUtil.isVal(key)) {
			return 0;
		}

		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.expireAt(key, unixTimestamp);
		} catch (Exception ex) {
			logger.error("EXPIRE error[key=" + key + " unixTimestamp=" + unixTimestamp + "]" + ex.getMessage(), ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return 0;
	}

	/**
	 * 截断一个List
	 * 
	 * @param key
	 *            列表key
	 * @param start
	 *            开始位置 从0开始
	 * @param end
	 *            结束位置
	 * @return 状态码
	 */
	public String trimList(String key, long start, long end) {
		if (!AssertUtil.isVal(key)) {
			return "-";
		}
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.ltrim(key, start, end);
		} catch (Exception ex) {
			logger.error("LTRIM 出错[key=" + key + " start=" + start + " end=" + end + "]" + ex.getMessage(), ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return "-";
	}

	/**
	 * 检查Set长度
	 * 
	 * @param key
	 * @return
	 */
	public long countSet(String key) {
		if (!AssertUtil.isVal(key)) 
			return 0;
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.scard(key);
		} catch (Exception ex) {
			logger.error("countSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return 0;
	}

	/**
	 * 添加到Set中(同时设置过期时间)
	 * 
	 * @param key
	 *            key值
	 * @param seconds
	 *            过期时间 单位s
	 * @param value
	 * @return
	 */
	public boolean addSet(String key, int seconds, String... value) {
		boolean result = addSet(key, value);
		if (result) {
			long i = expire(key, seconds);
			return i == 1;
		}
		return false;
	}

	/**
	 * 添加到Set中
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean addSet(String key, String... value) {
		if (!AssertUtil.isVal(key) || AssertUtil.isVal(value)) {
			return false;
		}
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			shardedJedis.sadd(key, value);
			return true;
		} catch (Exception ex) {
			logger.error("setList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * @param key
	 * @param value
	 * @return 判断值是否包含在set中
	 */
	public boolean containsInSet(String key, String value) {
		if (!AssertUtil.isVal(key) || AssertUtil.isVal(value)) {
			return false;
		}
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.sismember(key, value);
		} catch (Exception ex) {
			logger.error("setList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 获取Set
	 * 
	 * @param key
	 * @return
	 */
	public Set<String> getSet(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.smembers(key);
		} catch (Exception ex) {
			logger.error("getList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 从set中删除value
	 * 
	 * @param key
	 * @return
	 */
	public boolean removeSetValue(String key, String... value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			shardedJedis.srem(key, value);
			return true;
		} catch (Exception ex) {
			logger.error("getList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 从list中删除value 默认count 1
	 * 
	 * @param key
	 * @param values
	 *            值list
	 * @return
	 */
	public int removeListValue(String key, List<String> values) {
		return removeListValue(key, 1, values);
	}

	/**
	 * 从list中删除value
	 * 
	 * @param key
	 * @param count
	 * @param values
	 *            值list
	 * @return
	 */
	public int removeListValue(String key, long count, List<String> values) {
		int result = 0;
		if (values != null && values.size() > 0) {
			for (String value : values) {
				if (removeListValue(key, count, value)) {
					result++;
				}
			}
		}
		return result;
	}

	/**
	 * 从list中删除value
	 * 
	 * @param key
	 * @param count
	 *            要删除个数
	 * @param value
	 * @return
	 */
	public boolean removeListValue(String key, long count, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			shardedJedis.lrem(key, count, value);
			return true;
		} catch (Exception ex) {
			logger.error("getList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}
	
	/**
	 * 截取List
	 * 
	 * @param key
	 * @param start
	 *            起始位置
	 * @param end
	 *            结束位置
	 * @return
	 */
	public List<String> rangeList(String key, long start, long end) {
		if (!AssertUtil.isVal(key)) {
			return null;
		}
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.lrange(key, start, end);
		} catch (Exception ex) {
			logger.error("rangeList 出错[key=" + key + " start=" + start + " end=" + end + "]" + ex.getMessage(), ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 检查List长度
	 * 
	 * @param key
	 * @return
	 */
	public long countList(String key) {
		if (!AssertUtil.isVal(key)) {
			return 0;
		}
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.llen(key);
		} catch (Exception ex) {
			logger.error("countList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return 0;
	}

	/**
	 * 添加到List中(同时设置过期时间)
	 * 
	 * @param key
	 *            key值
	 * @param seconds
	 *            过期时间 单位s
	 * @param value
	 * @return
	 */
	public boolean addList(String key, int seconds, String... value) {
		boolean result = addList(key, value);
		if (result) {
			long i = expire(key, seconds);
			return i == 1;
		}
		return false;
	}

	/**
	 * 添加到List
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean addList(String key, String... value) {
		if (!AssertUtil.isVal(key) || AssertUtil.isVal(value)) {
			return false;
		}
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			shardedJedis.lpush(key, value);
			return true;
		} catch (Exception ex) {
			logger.error("setList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 添加到List(只新增)
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean addList(String key, List<String> list) {
		if (!AssertUtil.isVal(key) || AssertUtil.isVal(list) || list.size() == 0) {
			return false;
		}
		for (String value : list) {
			addList(key, value);
		}
		return true;
	}

	/**
	 * 获取List
	 * 
	 * @param key
	 * @return
	 */
	public List<String> getList(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.lrange(key, 0, -1);
		} catch (Exception ex) {
			logger.error("getList error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 设置HashSet对象
	 *
	 * @param domain
	 *            域名
	 * @param key
	 *            键值
	 * @param value
	 *            Json String or String value
	 * @return
	 */
	public boolean setHSet(String domain, String key, String value) {
		if (AssertUtil.isVal(value))
			return false;
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			shardedJedis.hset(domain, key, value);
			return true;
		} catch (Exception ex) {
			logger.error("setHSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 获得HashSet对象
	 *
	 * @param domain
	 *            域名
	 * @param key
	 *            键值
	 * @return Json String or String value
	 */
	public String getHSet(String domain, String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.hget(domain, key);
		} catch (Exception ex) {
			logger.error("getHSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 删除HashSet对象
	 *
	 * @param domain
	 *            域名
	 * @param key
	 *            键值
	 * @return 删除的记录数
	 */
	public long delHSet(String domain, String key) {
		ShardedJedis shardedJedis = null;
		long count = 0;
		try {
			shardedJedis = shardedJedisPool.getResource();
			count = shardedJedis.hdel(domain, key);
		} catch (Exception ex) {
			logger.error("delHSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return count;
	}

	/**
	 * 删除HashSet对象
	 *
	 * @param domain
	 *            域名
	 * @param key
	 *            键值
	 * @return 删除的记录数
	 */
	public long delHSet(String domain, String... key) {
		ShardedJedis shardedJedis = null;
		long count = 0;
		try {
			shardedJedis = shardedJedisPool.getResource();
			count = shardedJedis.hdel(domain, key);
		} catch (Exception ex) {
			logger.error("delHSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return count;
	}
	/**
	 * 判断key是否存在
	 *
	 * @param domain
	 *            域名
	 * @param key
	 *            键值
	 * @return
	 */
	public boolean exists(String key) {
		ShardedJedis shardedJedis = null;
		boolean isExist = false;
		try {
			shardedJedis = shardedJedisPool.getResource();
			isExist = shardedJedis.exists(key);
		} catch (Exception ex) {
			logger.error("existsHSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return isExist;
	}

	/**
	 * 判断key是否存在
	 *
	 * @param domain
	 *            域名
	 * @param key
	 *            键值
	 * @return
	 */
	public boolean existsHSet(String domain, String key) {
		ShardedJedis shardedJedis = null;
		boolean isExist = false;
		try {
			shardedJedis = shardedJedisPool.getResource();
			isExist = shardedJedis.hexists(domain, key);
		} catch (Exception ex) {
			logger.error("existsHSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return isExist;
	}
	

	/**
	 * 全局扫描hset
	 *
	 * @param match
	 *            field匹配模式
	 * @return
	 */
	public List<Map.Entry<String, String>> scanHSet(String domain, String match) {
		ShardedJedis shardedJedis = null;
		try {
			int cursor = 0;
			shardedJedis = shardedJedisPool.getResource();
			ScanParams scanParams = new ScanParams();
			scanParams.match(match);
			Jedis jedis = shardedJedis.getShard(domain);
			ScanResult<Map.Entry<String, String>> scanResult;
			List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>();
			do {
				scanResult = jedis.hscan(domain, String.valueOf(cursor), scanParams);
				list.addAll(scanResult.getResult());
				cursor = Integer.parseInt(scanResult.getStringCursor());
			} while (cursor > 0);
			return list;
		} catch (Exception ex) {
			logger.error("scanHSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 返回 domain 指定的哈希集中所有字段的value值
	 *
	 * @param domain
	 * @return
	 */

	public List<String> hvals(String domain) {
		ShardedJedis shardedJedis = null;
		List<String> retList = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			retList = shardedJedis.hvals(domain);
		} catch (Exception ex) {
			logger.error("hvals error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return retList;
	}

	/**
	 * 返回 domain 指定的哈希集中所有字段的key值
	 *
	 * @param domain
	 * @return
	 */

	public Set<String> hkeys(String domain) {
		ShardedJedis shardedJedis = null;
		Set<String> retList = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			retList = shardedJedis.hkeys(domain);
		} catch (Exception ex) {
			logger.error("hkeys error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return retList;
	}

	/**
	 * 返回 domain 指定的哈希key值总数
	 *
	 * @param domain
	 * @return
	 */
	public long lenHset(String domain) {
		ShardedJedis shardedJedis = null;
		long retList = 0;
		try {
			shardedJedis = shardedJedisPool.getResource();
			retList = shardedJedis.hlen(domain);
		} catch (Exception ex) {
			logger.error("hkeys error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return retList;
	}

	/**
	 * 设置排序集合
	 *
	 * @param key
	 * @param score
	 * @param value
	 * @return
	 */
	public boolean setSortedSet(String key, long score, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			shardedJedis.zadd(key, score, value);
			return true;
		} catch (Exception ex) {
			logger.error("setSortedSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 获得排序集合
	 *
	 * @param key
	 * @param startScore
	 * @param endScore
	 * @param orderByDesc
	 * @return
	 */
	public Set<String> getSoredSet(String key, long startScore, long endScore, boolean orderByDesc) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			if (orderByDesc) {
				return shardedJedis.zrevrangeByScore(key, endScore, startScore);
			} else {
				return shardedJedis.zrangeByScore(key, startScore, endScore);
			}
		} catch (Exception ex) {
			logger.error("getSoredSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 计算排序长度
	 *
	 * @param key
	 * @param startScore
	 * @param endScore
	 * @return
	 */
	public long countSoredSet(String key, long startScore, long endScore) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			Long count = shardedJedis.zcount(key, startScore, endScore);
			return count == null ? 0L : count;
		} catch (Exception ex) {
			logger.error("countSoredSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return 0L;
	}

	/**
	 * 删除排序集合
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean delSortedSet(String key, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			long count = shardedJedis.zrem(key, value);
			return count > 0;
		} catch (Exception ex) {
			logger.error("delSortedSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 获得排序集合
	 *
	 * @param key
	 * @param startRange
	 * @param endRange
	 * @param orderByDesc
	 * @return
	 */
	public Set<String> getSoredSetByRange(String key, int startRange, int endRange, boolean orderByDesc) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			if (orderByDesc) {
				return shardedJedis.zrevrange(key, startRange, endRange);
			} else {
				return shardedJedis.zrange(key, startRange, endRange);
			}
		} catch (Exception ex) {
			logger.error("getSoredSetByRange error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 获得排序打分
	 *
	 * @param key
	 * @return
	 */
	public Double getScore(String key, String member) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.zscore(key, member);
		} catch (Exception ex) {
			logger.error("getSoredSet error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 设置key对应字符串value,并且设置key在给定的seconds时间之后超时过期。这个命令等效于执行下面的命令:<br/>
	 * SET mykey value
	 * EXPIRE mykey seconds
	 * @param key
	 * @param value
	 * @param second
	 * @return
	 */
	public boolean set(String key, String value, int second) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			String result = shardedJedis.setex(key, second, value);
			if ("OK".equals(result))
				return true;
		} catch (Exception ex) {
			logger.error("set error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	
	/**
	 * 将键key设定为指定的“字符串”值。<br/>
	 * 如果 key 已经保存了一个值,那么这个操作会直接覆盖原来的值,并且忽略原始类型。<br/>
	 * 当set命令执行成功之后,之前设置的过期时间都将失效
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(String key, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			String result = shardedJedis.set(key, value);
			if ("OK".equals(result))
				return true;
		} catch (Exception ex) {
			logger.error("set error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}
	
	
	
	/**
	 * 将键key设定为指定的“字符串”值。<br/>
	 * 如果 key 已经保存了一个值,那么这个操作会直接覆盖原来的值,并且忽略原始类型。<br/>
	 * 当set命令执行成功之后,之前设置的过期时间都将失效
	 * @param key
	 * @param value
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean setObject(String key, Object value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			byte[] keyBytes = this.keySerializer.serialize(key);
			byte[] valueBytes = this.valueSerializer.serialize(value);
			String result = shardedJedis.set(keyBytes, valueBytes);
			if ("OK".equals(result))
				return true;
		} catch (Exception ex) {
			logger.error("set error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}
	
	/**
	 * 设置key对应字符串value,并且设置key在给定的seconds时间之后超时过期。这个命令等效于执行下面的命令:<br/>
	 * @param key
	 * @param value
	 * @param second
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean setObject(String key, Object value, int second) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			byte[] keyBytes = this.keySerializer.serialize(key);
			byte[] valueBytes = this.valueSerializer.serialize(value);
			String result = shardedJedis.setex(keyBytes, second, valueBytes);
			if ("OK".equals(result))
				return true;
		} catch (Exception ex) {
			logger.error("set error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 返回key的value。如果key不存在,返回特殊值nil。如果key的value不是string,就返回错误,因为GET只处理string类型的values。
	 * @param key
	 * @param defaultValue key不存在时 返回的默认值
	 * @return key对应的value,或者nil(key不存在时)
	 */
	public String get(String key, String defaultValue) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.get(key) == null ? defaultValue : shardedJedis.get(key);
		} catch (Exception ex) {
			logger.error("get error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return defaultValue;
	}	
	
	/**
	 * 返回key的value。如果key不存在,返回特殊值nil。如果key的value不是string,就返回错误,因为GET只处理string类型的values。
	 * @param key
	 * @return key对应的value,或者nil(key不存在时)
	 */
	public String get(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			
			return shardedJedis.get(key);
		} catch (Exception ex) {
			logger.error("get error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}
	
	/**
	 * 返回key的value。如果key不存在,返回特殊值nil。如果key的value不是string,就返回错误,因为GET只处理string类型的values。
	 * @param key
	 * @return key对应的value,或者nil(key不存在时)
	 */
	@SuppressWarnings("unchecked")
	public <T> T getObject(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			byte[] keyBytes = this.keySerializer.serialize(key);
			byte[] valueBytes = shardedJedis.get(keyBytes);
			return (T)this.valueSerializer.deserialize(valueBytes);
		} catch (Exception ex) {
			logger.error("get error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return null;
	}

	/**
	 * 如果删除的key不存在,则直接忽略。 <br/>
	 * @param key
	 * @return integer-reply: 被删除的keys的数量
	 */
	public boolean del(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			shardedJedis.del(key);
			return true;
		} catch (Exception ex) {
			logger.error("del error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}
	
	/**
	 * 如果删除的key不存在,则直接忽略。 <br/>
	 * @param key
	 * @return integer-reply: 被删除的keys的数量
	 */
	@SuppressWarnings("unchecked")
	public boolean delObject(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			byte[] keyBytes = this.keySerializer.serialize(key);
			shardedJedis.del(keyBytes);
			return true;
		} catch (Exception ex) {
			logger.error("del error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return false;
	}

	/**
	 * 对存储在指定key的数值执行原子的加1操作。<br/>
	 * 如果指定的key不存在,那么在执行incr操作之前,会先将它的值设定为0。
	 * 如果指定的key中存储的值不是字符串类型(fix:)或者存储的字符串类型不能表示为一个整数,
	 * 那么执行这个命令时服务器会返回一个错误(eq:(error) ERR value is not an integer or out of range)。
	 * 这个操作仅限于64位的有符号整型数据。<br/>
	 * 
	 * 
	 * <h1>注意</h1>
	 * 由于redis并没有一个明确的类型来表示整型数据,所以这个操作是一个字符串操作。<br/>
	 * 执行这个操作的时候,key对应存储的字符串被解析为10进制的64位有符号整型
	 * @param key
	 * @return
	 */
	public long incr(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.incr(key);
		} catch (Exception ex) {
			logger.error("incr error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return 0;
	}

	/**
	 * 对key对应的数字做减1操作。如果key不存在,那么在操作之前,这个key对应的值会被置为0。
	 * 如果key有一个错误类型的value或者是一个不能表示成数字的字符串,就返回错误。
	 * 这个操作最大支持在64位有符号的整型数字。查看命令INCR了解关于增减操作的额外信息。
	 * @param key
	 * @return
	 */
	public long decr(String key) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.decr(key);
		} catch (Exception ex) {
			logger.error("incr error.", ex);
			returnBrokenResource(shardedJedis);
		} finally {
			returnResource(shardedJedis);
		}
		return 0;
	}

	/**
	 * 发布消息
	 * @param channel
	 * @param message
	 */
	public void publish(String channel, String message) {
		this.publish(channel, message, null);
	}
	
	/**
	 * 发布消息
	 * @param channel
	 * @param message
	 * @param key
	 */
	public void publish(String channel, String message, String key) {
		ShardedJedis shardedJedis = null;
		try {
			if (AssertUtil.isVal(key)) {
				Jedis jedis = shardedJedisPool.getResource().getShard(key);
				if (AssertUtil.isVal(key)) {
					jedis.publish(channel, message);
				} else {
					throw new JedisException("没有找到与KEY=" + key +"对应的节点");
				}
				return;
			}
			Collection<Jedis> allShards = shardedJedisPool.getResource().getAllShards();
			for (Jedis jedis : allShards) {
				jedis.publish(channel, message);
			}
		} catch (Exception ex) {
			logger.error("incr error.", ex);
			returnBrokenResource(shardedJedis);
			throw ex;
		} finally {
			returnResource(shardedJedis);
		}
	}
	
	
	/**
	 * 断开连接,并且回收资源, 用于catch 异常使用
	 * @param shardedJedis
	 */
	private void returnBrokenResource(ShardedJedis shardedJedis) {
		try {
			shardedJedisPool.returnBrokenResource(shardedJedis);
		} catch (Exception e) {
			logger.error("returnBrokenResource error.", e);
		}
	}

	/**
	 * 回收资源
	 * @param shardedJedis
	 */
	private void returnResource(ShardedJedis shardedJedis) {
		try {
			shardedJedisPool.returnResource(shardedJedis);
		} catch (Exception e) {
			logger.error("returnResource error.", e);
		}
	}

}

 

分享到:
评论

相关推荐

    spring data redis api jar

    使用Spring Data Redis API,开发者可以极大地简化Redis的编程模型,通过面向对象的方式处理数据操作,提高代码的可读性和可维护性。此外,由于Spring Data的统一设计,使得切换到其他数据存储系统时,代码改动最小...

    Redis java 实例 包含jar包

    Jedis是Java社区中最常用的Redis客户端,它提供了丰富的API来操作Redis服务器。在Java项目中,可以通过Maven或Gradle将Jedis库添加为依赖。在Maven的pom.xml文件中,你可以添加以下依赖: ```xml &lt;groupId&gt;redis....

    redis java demo

    在Java编程中,我们可以利用Jedis库与Redis服务器进行交互。本教程将深入讲解如何在Java环境中设置Redis并实现一个简单的示例。 首先,我们需要在项目中引入Jedis库。如果你使用的是Maven,可以在pom.xml文件中添加...

    java操作redis

    Java作为广泛使用的编程语言,提供了多种库来与Redis进行交互,使得开发者可以方便地在Java应用程序中利用Redis的强大功能。下面将详细讨论如何在Java中操作Redis,以及相关的关键知识点。 首先,为了在Java中操作...

    异步redis + java源码

    Java作为广泛使用的编程语言,与Redis的结合应用是常见的开发实践。本篇文章将深入探讨“异步Redis”在Java环境中的实现,以及如何通过源码理解其工作原理。 异步Redis通信模式主要利用非阻塞I/O(Non-blocking I/O...

    资料.rar redis java jar包 window下redis软件

    Java是广泛使用的编程语言,与Redis结合使用时,可以借助Java客户端库进行交互。 在Windows环境下运行Redis,你需要下载Redis的Windows版本。Redis通常在Linux系统上运行,但通过第三方移植,也可以在Windows上顺利...

    java-redis jar

    首先,Java Redis的客户端库主要有Jedis和Lettuce两个,它们都是Java编写的Redis客户端,提供丰富的API供开发者操作Redis。Jedis是较早且广泛使用的库,支持各种Redis命令,适用于大部分场景;Lettuce则提供了更现代...

    大数据Redis系统视频教程

    讲解Redis单机环境环境、shell操作、Java API编程,以及持久化方案、主从复制架构、Sentinel架构、集群等知识点。 课程亮点 1,知识体系完备,从小白到大神各阶段读者均能学有所获。 2,生动形象,化繁为简,讲解...

    java api 常备库

    Java API是Java编程语言中的一组预定义函数,它们提供了丰富的功能,使开发者能够更高效地构建应用程序。这里我们将深入探讨Java API中的几个关键部分,包括与Ajax、EasyUI、MySQL、Redis、Linux以及JQuery相关的...

    redis-开发接口参考文档 - 2.docx

    **JedisClient** 是一个由 Redis 官方推荐的 Java 客户端,它实现了对 Redis 各类 API 的封装调用。通过 JedisClient,开发者可以方便地操作 Redis 数据库,实现数据的存储与读取等功能。 **Jedis** 源码工程地址:...

    java_redis简单案例

    Java是一种广泛应用的编程语言,而Redis则是一种高性能的键值数据库,常用于缓存和实时数据处理。本资源"java_redis简单案例"提供了一个演示如何在Java应用中集成Redis的实例,帮助开发者了解两者的基本用法。 首先...

    完整的java操作redis demo

    Jedis是Java社区广泛使用的Redis客户端,提供了丰富的API来操作Redis服务器。在这个“完整的java操作redis demo”中,我们不仅可以看到如何使用Jedis进行基本的Redis操作,还能学习到如何结合Java处理Excel数据,这...

    Java操作Redis的多种数据类型

    而Java作为广泛使用的后端编程语言,提供了丰富的库来与Redis进行交互。本文将深入探讨如何使用Java操作Redis的四种主要数据类型:字符串(String)、列表(List)、哈希(Hash)和集合(Set)。 首先,我们来看**...

    Java-redis-demo

    11. **Spring Data Redis**: 如果你的项目使用了Spring框架,Spring Data Redis模块可以简化与Redis的集成,提供了一套基于注解的编程模型。 12. **性能调优**: 使用Redis时,需要关注数据结构的选择、过期策略、...

    Java操作redis小案例

    Redis是一个高性能的键值数据库,常用于缓存和消息中间件,而Java作为一种广泛使用的编程语言,有着丰富的库和框架来与Redis进行交互。本篇文章将深入探讨如何使用Java操作Redis,并通过一个小型案例来展示其实现...

    java连接Redis资源包(最新)

    Java是广泛使用的编程语言,Java开发者常常需要通过Java连接Redis来实现数据交互。 本资源包“java连接Redis资源包(最新)”提供了适用于Windows和Linux环境的Redis安装文件,确保无论你在哪种操作系统上,都能...

    Redisson Easy Redis Java客户端和实时数据平台SyncAsyncRxJavaReactive A.zip

    总结来说,Redisson作为一个强大的Java Redis客户端,提供了丰富的API和多种编程模型,适应不同场景的需求,是开发基于Redis的实时数据平台的理想选择。无论是简单的键值存储还是复杂的分布式服务,都能在Redisson的...

    自定义注解解决API接口幂等设计防止表单重复提交(生成token存放到redis中)

    接下来,我们需要编写一个处理器,通常是一个AOP(面向切面编程)的切面类,用于拦截标注了`@Idempotent`的方法。这个切面会在方法执行前后进行操作,例如: ```java import org.aspectj.lang.ProceedingJoinPoint;...

    java-基于redis限流系统

    总的来说,通过结合Java编程和Redis的数据结构与操作,我们可以构建出一个强大而灵活的限流系统,有效地保护服务免受过载冲击,维持系统的稳定运行。在设计和实现过程中,还需要考虑系统的可扩展性、容错性和监控...

Global site tag (gtag.js) - Google Analytics