JedisCluster实现redis的keys命令的方法

由于JedisCluster没有提供对keys命令的封装,只能自己实现:


先定义接口。使用TreeSet返回,是为了可以方便地利用它的first()方法:

public interface IRedisOperator {

	/**
	 * 根据pattern 获取所有的keys
	 * @param pattern
	 * @return
	 */
	TreeSet keys(String pattern);
}

实现类:

public class RedisOperator implements IRedisOperator {

	public final static Logger logger = LoggerFactory.getLogger(RedisOperator.class);

	@Autowired
	private JedisCluster jedisCluster;

	@Override
	public TreeSet keys(String pattern){
		logger.debug("Start getting keys...");
		TreeSet keys = new TreeSet<>();
		Map clusterNodes = jedisCluster.getClusterNodes();
		for(String k : clusterNodes.keySet()){
			logger.debug("Getting keys from: {}", k);
			JedisPool jp = clusterNodes.get(k);
			Jedis connection = jp.getResource();
			try {
				keys.addAll(connection.keys(pattern));
			} catch(Exception e){
				logger.error("Getting keys error: {}", e);
			} finally{
				logger.debug("Connection closed.");
				connection.close();//用完一定要close这个链接!!!
			}
		}
		logger.debug("Keys gotten!");
		return keys;
	}
}

调用:

		TreeSet keys = redisOperator.keys(prefix);
		Map data = new LinkedHashMap<>();
		data.put("prefix", prefix);
		data.put("count", keys.size());
		String type = "unknown";
		if(keys.size()>0){
			type = redisOperator.type(keys.first());
		}
		data.put("type", type);


你可能感兴趣的:(缓存)