JedisCluster實現redis的keys命令的方法
阿新 • • 發佈:2018-12-25
由於JedisCluster沒有提供對keys命令的封裝,只能自己實現:
先定義介面。使用TreeSet返回,是為了可以方便地利用它的first()方法:
public interface IRedisOperator {
/**
* 根據pattern 獲取所有的keys
* @param pattern
* @return
*/
TreeSet<String> keys(String pattern);
}
實現類:
public class RedisOperator implements IRedisOperator { public final static Logger logger = LoggerFactory.getLogger(RedisOperator.class); @Autowired private JedisCluster jedisCluster; @Override public TreeSet<String> keys(String pattern){ logger.debug("Start getting keys..."); TreeSet<String> keys = new TreeSet<>(); Map<String, JedisPool> 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<String> keys = redisOperator.keys(prefix); Map<String, Object> 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);