Redis學習筆記-RedisCluster安裝部署和API使用

1、Ruby安裝

$tar -xzvf ruby-2.2.4.tar.gz

$./configure

$make

$make install

 

2、Redis安裝

$tar -zxvf redis-3.2.3.tar.gz

$make && make install

 

3、Ruby和Redis的接口

$gem install redis 或 $gem install redis -v 3.3.3  在線

$gem install -l ./redis-3.3.1.gem  離線

 

4、新建目錄redis-3.2.3/cluster/6373、redis-3.2.3/cluster/6374、redis-3.2.3/cluster/6375、redis-3.2.3/cluster/6376、redis-3.2.3/cluster/6377、redis-3.2.3/cluster/6378、redis-3.2.3/pids、redis-3.2.3/dbs、redis-3.2.3/logs,修改相應的配置

​
bind 192.168.0.10
protected-mode yes
port 6373
tcp-backlog 511
timeout 300
tcp-keepalive 300
daemonize yes
supervised no
pidfile /home/user/Software/redis-3.2.3/pids/redis_6373.pid
loglevel notice
logfile /home/user/Software/redis-3.2.3/logs/redis_6373.log
databases 16
save 900 1
save 300 10
save 60 10000
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /home/user/Software/redis-3.2.3/dbs/6373
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
cluster-enabled yes
cluster-config-file /home/user/Software/redis-3.2.3/cluster/conf/nodes-6373.conf
cluster-node-timeout 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes

​

5、啓動腳本

#!/bin/bash

ps -ef|grep redis|awk '{print $2}'|xargs kill -9

rm -rf /home/user/Software/redis-3.2.3/dbs/6373/*
rm -rf /home/user/Software/redis-3.2.3/dbs/6374/*
rm -rf /home/user/Software/redis-3.2.3/dbs/6375/*
rm -rf /home/user/Software/redis-3.2.3/dbs/6376/*
rm -rf /home/user/Software/redis-3.2.3/dbs/6377/*
rm -rf /home/user/Software/redis-3.2.3/dbs/6378/*

rm -rf /home/user/Software/redis-3.2.3/cluster/conf/*

redis-server /home/user/Software/redis-3.2.3/cluster/6373/redis.conf
redis-server /home/user/Software/redis-3.2.3/cluster/6374/redis.conf
redis-server /home/user/Software/redis-3.2.3/cluster/6375/redis.conf
redis-server /home/user/Software/redis-3.2.3/cluster/6376/redis.conf
redis-server /home/user/Software/redis-3.2.3/cluster/6377/redis.conf
redis-server /home/user/Software/redis-3.2.3/cluster/6378/redis.conf

/home/user/Software/redis-3.2.3/src/redis-trib.rb create --replicas 1 192.168.0.10:6373 192.168.0.10:6374 192.168.0.10:6375 192.168.0.10:6376 192.168.0.10:6377 192.168.0.10:6378

$ redis-cli -c -h 192.168.0.10 -p 6373

192.168.0.10:6373> cluster info

192.168.0.10:6373> cluster nodes

 

6、異常問題處理記錄

jemalloc/jemalloc.h: No such file or directory

make MALLOC=libc

 

cannot load such file -- zlib

進入ruby源碼文件夾,安裝ruby自身提供的zlib包

$cd ext/zlib

$ruby ./extconf.rb

$make

$make install

 

7、Java API 操作 Redis Cluster

#Redis Configuration
spring.redis.pool.maxActive=1024 
spring.redis.pool.maxWaitMillis=-1
spring.redis.pool.maxTotal=1000
spring.redis.pool.maxWait=1000    
spring.redis.pool.maxIdle=20    
spring.redis.pool.minIdle=10    
spring.redis.pool.testOnBorrow=true
spring.redis.pool.testOnReturn=true
spring.redis.pool.timeout=300000 
spring.redis.pool.minEvictableIdleTimeMillis=100000
spring.redis.pool.timeBetweenEvictionRunsMillis=100000

spring.redis.cluster.address=192.168.0.10:6373,192.168.0.10:6374,192.168.0.10:6375,192.168.0.10:6376,192.168.0.10:6377,192.168.0.10:6378
spring.redis.cluster.timeout=300000
spring.redis.cluster.maxRedirections=6
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.cisiondata.utils.redis.JedisClusterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.Jedis;

@Configuration
@ConditionalOnClass({Jedis.class})
public class RedisConfiguration {

	private Logger LOG = LoggerFactory.getLogger(RedisConfiguration.class);
	
	@Bean
	@ConfigurationProperties(prefix = "spring.redis.pool")
	public GenericObjectPoolConfig genericObjectPoolConfig() {
		return new GenericObjectPoolConfig();
	}
	
	@Bean(name = "jedisCluster")
	@ConfigurationProperties(prefix = "spring.redis.cluster")
	public JedisClusterFactory jedisClusterFactory() {
		JedisClusterFactory jedisClusterFactory = new JedisClusterFactory();
		jedisClusterFactory.setGenericObjectPoolConfig(genericObjectPoolConfig());
		LOG.info("Jedis Cluster Factory Initialize Success!");
		return jedisClusterFactory;
	}
	
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.cisiondata.utils.reflect.ReflectUtils;
import org.cisiondata.utils.serde.SerializerUtils;
import org.cisiondata.utils.spring.SpringBeanFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;
import redis.clients.util.SafeEncoder;

public class RedisClusterUtils {
	
	private Logger LOG = LoggerFactory.getLogger(RedisClusterUtils.class);
	
	private JedisCluster jedisCluster = null;

	private RedisClusterUtils() {
		this.jedisCluster = (JedisCluster) SpringBeanFactory.getBean("jedisCluster");
	}

	private static class RedisClusterUtilsHolder {
		public static RedisClusterUtils INSTANCE = new RedisClusterUtils();
	}

	public static RedisClusterUtils getInstance() {
		return RedisClusterUtilsHolder.INSTANCE;
	}
	
	public JedisCluster getJedisCluster() {
		return jedisCluster;
	}
	
	/**
	 * 讀取keys
	 * @param pattern
	 * @return
	 */
	public Set<String> keys(String pattern) {
		Set<String> keys = new HashSet<String>();
		Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
		for (Map.Entry<String, JedisPool> entry : clusterNodes.entrySet()) {
			Jedis connection = entry.getValue().getResource();
			try {
				Set<byte[]> keysByte = connection.keys(SafeEncoder.encode(pattern));
				for (byte[] keyByte : keysByte) {
					try {
						keys.add((String) SerializerUtils.read(keyByte));
					} catch (Exception e) {
						keys.add(SafeEncoder.encode(keyByte));
					}
				}
			} finally {
				connection.close();
			}
		}
		return keys;
	}
	
	/**
	 * 返回key的類型
	 * The type can be one of "none", string", "list", "set", "zset", "hash"
	 * @param key
	 * @return
	 */
	public String type(String key) {
		try {
			return jedisCluster.type(SerializerUtils.write(key));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return "none";
	}
	
	/**
	 * 是否存在key
	 * @param key
	 * @return
	 */
	public boolean exists(String key) {
		try {
			return jedisCluster.exists(SerializerUtils.write(key));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return false;
	}
	
	/**
	 * 設置過期時間
	 * @param key
	 * @param seconds
	 * @return
	 */
	public Long expire(String key, int seconds) {
		try {
			return jedisCluster.expire(SerializerUtils.write(key), seconds);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0L;
	}
	
	/**
	 * 緩存數據
	 * @param key
	 * @param value
	 */
	public void set(String key, Object value) {
		try {
			jedisCluster.set(SerializerUtils.write(key), SerializerUtils.write(value));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}

	/**
	 * 緩存數據
	 * @param key
	 * @param value
	 */
	public void set(Object key, Object value) {
		try {
			jedisCluster.set(SerializerUtils.write(key), SerializerUtils.write(value));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 緩存數據並設置過期時間
	 * @param key
	 * @param value
	 * @param expireTime
	 */
	public void set(String key, Object value, int expireTime) {
		try {
			byte[] cache_key = SerializerUtils.write(key);
			jedisCluster.set(cache_key, SerializerUtils.write(value));
			jedisCluster.expire(cache_key, expireTime);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 緩存數據並設置過期時間
	 * @param key
	 * @param value
	 * @param expireTime
	 */
	public void set(Object key, Object value, int expireTime) {
		try {
			byte[] cache_key = SerializerUtils.write(key);
			jedisCluster.set(cache_key, SerializerUtils.write(value));
			jedisCluster.expire(cache_key, expireTime);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 緩存數據
	 * @param key
	 * @param value
	 * @return
	 */
	public Long setnx(Object key, Object value) {
		try {
			return jedisCluster.setnx(SerializerUtils.write(key), SerializerUtils.write(value));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0L;
	}
	
	/**
	 * 遞增KEY
	 * @param key
	 * @return
	 */
	public Long incr(Object key) {
		try {
			return jedisCluster.incr(SerializerUtils.write(key));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0L;
	}
	
	/**
	 * 遞增KEY
	 * @param key
	 * @param incr
	 * @return
	 */
	public Long incrBy(Object key, long incr) {
		try {
			return jedisCluster.incrBy(SerializerUtils.write(key), incr);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0L;
	}
	
	/**
	 * 讀取數據
	 * @param key
	 * @return
	 */
	public Object get(String key) {
		if (StringUtils.isBlank(key)) return null;
		try {
			byte[] value = jedisCluster.get(SerializerUtils.write(key));
			if (null != value && value.length != 0) {
				return SerializerUtils.read(value);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 讀取數據
	 * @param key
	 * @return
	 */
	public Object get(Object key) {
		if (null == key) return null;
		try {
			byte[] value = jedisCluster.get(SerializerUtils.write(key));
			if (null != value && value.length != 0) {
				return SerializerUtils.read(value);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 讀取數據
	 * @param key
	 * @param value
	 * @return
	 */
	public Object getSet(Object key, Object value) {
		if (null == key || null == value) return null;
		try {
			byte[] ovalue = jedisCluster.getSet(SerializerUtils.write(key), SerializerUtils.write(value));
			if (null != ovalue && ovalue.length != 0) {
				return SerializerUtils.read(ovalue);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 刪除KEY
	 * @param key
	 * @return
	 */
	public Long delete(String key) {
		if (StringUtils.isBlank(key)) return null;
		try {
			return jedisCluster.del(SerializerUtils.write(key));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 刪除KEY
	 * @param key
	 * @return
	 */
	public Long delete(Object key) {
		if (null == key) return null;
		try {
			return jedisCluster.del(SerializerUtils.write(key));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 新增SET數據集合
	 * @param key
	 * @param members
	 * @return
	 */
	public long sadd(String key, String... members) {
		try {
			return jedisCluster.sadd(key, members);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * 新增SET數據集合
	 * @param key
	 * @param members
	 * @return
	 */
	public long sadd(String key, Object... members) {
		try {
			if (null == members|| members.length == 0) return 0;
			byte[][] bmembers = new byte[members.length][];
			for (int i = 0, len = members.length; i < len; i++) {
				bmembers[i] = SerializerUtils.write(members[i]);
			}
			return jedisCluster.sadd(SerializerUtils.write(key), bmembers);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * SET數據集合成員是否存在
	 * @param key
	 * @param member
	 * @return
	 */
	public boolean sismember(String key, String member) {
		try {
			return jedisCluster.sismember(key, member);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return false;
	}
	
	/**
	 * SET數據集合長度
	 * @param key
	 * @return
	 */
	public long scard(String key) {
		try {
			return jedisCluster.scard(key);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * 獲取KEY中SET數據集合
	 * @param key
	 * @return
	 */
	public Set<String> smembers(String key) {
		try {
			return jedisCluster.smembers(key);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 獲取KEY中SET數據集合
	 * @param key
	 * @return
	 */
	public Set<Object> smembers2obj(String key) {
		Set<Object> results = new HashSet<Object>();
		try {
			Set<byte[]> bresults = jedisCluster.smembers(SerializerUtils.write(key));
			if (null == bresults || bresults.isEmpty()) return results;
			for (byte[] bresult : bresults) {
				results.add(SerializerUtils.read(bresult));
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return results;
	}
	
	/**
	 * 刪除SET數據集合
	 * @param key
	 * @param members
	 * @return
	 */
	public long srem(String key, String... members) {
		try {
			return jedisCluster.srem(key, members);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * 刪除SET數據集合
	 * @param key
	 * @param members
	 * @return
	 */
	public long srem(String key, Object... members) {
		try {
			if (null == members|| members.length == 0) return 0;
			byte[][] bmembers = new byte[members.length][];
			for (int i = 0, len = members.length; i < len; i++) {
				bmembers[i] = SerializerUtils.write(members[i]);
			}
			return jedisCluster.srem(SerializerUtils.write(key), bmembers);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * 隊列插入數據
	 * @param key
	 * @param value
	 * @return
	 */
	public long listPush(String key, Object value) {
		try {
			return jedisCluster.lpush(SerializerUtils.write(key), SerializerUtils.write(value));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * 隊列取出數據
	 * @param key
	 * @return
	 */
	public Object listPop(String key) {
		try {
			byte[] returnObject = jedisCluster.rpop(SerializerUtils.write(key));
			if (null != returnObject && returnObject.length != 0) {
				return SerializerUtils.read(returnObject);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 隊列數據長度
	 * @param key
	 * @return
	 */
	public long listLength(String key) {
		try {
			return jedisCluster.llen(SerializerUtils.write(key));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * Hash緩存數據
	 * @param key
	 * @param field
	 * @param value
	 * @return
	 */
	public long hset(String key, String field, Object value) {
		try {
			return jedisCluster.hset(SerializerUtils.write(key), 
				SerializerUtils.write(field), SerializerUtils.write(value));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * Hash緩存數據
	 * @param key
	 * @param map
	 * @return
	 */
	public String hset(String key, Map<String, ?> value) {
		try {
			Map<byte[], byte[]> hash = new HashMap<byte[], byte[]>();
			for (Map.Entry<String, ?> entry : value.entrySet()) {
				hash.put(SerializerUtils.write(entry.getKey()), 
					SerializerUtils.write(entry.getValue()));
			}
			return jedisCluster.hmset(SerializerUtils.write(key), hash);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * Hash緩存實體Bean
	 * @param key
	 * @param value
	 * @param expireTime
	 * @return
	 */
	public String hsetBean(Object key, Object value, int expireTime) {
		try {
			if (null == value) return null;
			Map<byte[], byte[]> hash = new HashMap<byte[], byte[]>();
			Map<String, Object> map = ReflectUtils.convertObjectToObjectMap(value);
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				hash.put(SerializerUtils.write(entry.getKey()), 
					SerializerUtils.write(entry.getValue()));
			}
			byte[] keyBytes = SerializerUtils.write(key);
			String result = jedisCluster.hmset(keyBytes, hash);
			jedisCluster.expire(keyBytes, expireTime);
			return result;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * Hash緩存實體Bean
	 * @param key
	 * @param value
	 * @return
	 */
	public String hsetBean(Object key, Object value) {
		try {
			if (null == value) return null;
			Map<byte[], byte[]> hash = new HashMap<byte[], byte[]>();
			Map<String, Object> map = ReflectUtils.convertObjectToObjectMap(value);
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				hash.put(SerializerUtils.write(entry.getKey()), 
					SerializerUtils.write(entry.getValue()));
			}
			return jedisCluster.hmset(SerializerUtils.write(key), hash);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * Hash是否存在field
	 * @param key
	 * @param field
	 * @return
	 */
	public boolean hexists(String key, String field) {
		try {
			return jedisCluster.hexists(SerializerUtils.write(key), SerializerUtils.write(field));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return false;
	}
	
	/**
	 * Hash字段自增數據
	 * @param key
	 * @param field
	 * @param value
	 * @return
	 */
	public long hincrBy(String key, String field, long value) {
		try {
			return jedisCluster.hincrBy(SerializerUtils.write(key), 
				SerializerUtils.write(field), value);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * Hash讀取數據
	 * @param key
	 * @param field
	 * @return
	 */
	public Object hget(String key, String field) {
		try {
			byte[] returnObject = jedisCluster.hget(SerializerUtils.write(key), SerializerUtils.write(field));
			if (null != returnObject && returnObject.length != 0) {
				return SerializerUtils.read(returnObject);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	public Object hgetBean(String key, Class<?> entityClass) {
		try {
			Map<byte[], byte[]> hash = jedisCluster.hgetAll(SerializerUtils.write(key));
			if (null != hash && !hash.isEmpty()) {
				Map<String, Object> map = new HashMap<String, Object>();
				for (Map.Entry<byte[], byte[]> entry : hash.entrySet()) {
					map.put((String) SerializerUtils.read(entry.getKey()), 
						SerializerUtils.read(entry.getValue()));
				}
				Object returnObject = entityClass.newInstance();
				ReflectUtils.convertObjectMapToObject(map, returnObject);
				return returnObject;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * Hash讀取數據
	 * @param key
	 * @return
	 */
	public Map<String, Object> hgetAll(String key) {
		try {
			Map<byte[], byte[]> returnObject = jedisCluster.hgetAll(SerializerUtils.write(key));
			if (null != returnObject && !returnObject.isEmpty()) {
				Map<String, Object> map = new HashMap<String, Object>();
				for (Map.Entry<byte[], byte[]> entry : returnObject.entrySet()) {
					map.put((String) SerializerUtils.read(entry.getKey()), 
						SerializerUtils.read(entry.getValue()));
				}
				return map;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * Hash刪除fields
	 * @param key
	 * @param fields
	 * @return
	 */
	public long hdel(String key, String... fields) {
		try {
			return jedisCluster.hdel(SerializerUtils.write(key), SerializerUtils.write(fields));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * SortedSet新增成員
	 * @param key
	 * @param member
	 * @param score
	 * @return
	 */
	public long zadd(String key, Object member, double score) {
		try {
			return jedisCluster.zadd(SerializerUtils.write(key), score, SerializerUtils.write(member));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * SortedSet新增成員
	 * @param key
	 * @param member
	 * @param score
	 * @return
	 */
	public long zadd(String key, Map<Object, Double> members) {
		try {
			Map<byte[], Double> scoreMembers = new HashMap<byte[], Double>();
			for (Map.Entry<Object, Double> entry : members.entrySet()) {
				scoreMembers.put(SerializerUtils.write(entry.getKey()), entry.getValue());
			}
			return jedisCluster.zadd(SerializerUtils.write(key), scoreMembers);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * SortedSet讀取成員
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<Object> zrange(String key, long start, long end) {
		Set<Object> results = new HashSet<Object>();
		try {
			Set<byte[]> bresults = jedisCluster.zrange(SerializerUtils.write(key), start, end);
			if (null == bresults || bresults.isEmpty()) return results;
			for (byte[] bresult : bresults) {
				results.add(SerializerUtils.read(bresult));
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return results;
	}
	
	/**
	 * SortedSet讀取成員和分數
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public List<Map.Entry<String, Double>> zrangeWithScores(String key, long start, long end) {
		List<Map.Entry<String, Double>> resultList = new ArrayList<Map.Entry<String, Double>>();
		try {
			Set<Tuple> tuples = jedisCluster.zrangeWithScores(SerializerUtils.write(key), start, end);
			if (null == tuples || tuples.isEmpty()) return resultList;
			Map<String, Double> results = new HashMap<String, Double>();
			for (Tuple tuple : tuples) {
				results.put(String.valueOf(SerializerUtils.read(tuple.getBinaryElement())), tuple.getScore());
			}
			resultList.addAll(results.entrySet());
			Collections.sort(resultList, new Comparator<Map.Entry<String, Double>>(){
				@Override
				public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
					return o1.getValue().compareTo(o2.getValue());
				}
			});
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return resultList;
	}
	
	/**
	 * SortedSet讀取成員
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<Object> zrevrange(String key, long start, long end) {
		Set<Object> results = new HashSet<Object>();
		try {
			Set<byte[]> bresults = jedisCluster.zrevrange(SerializerUtils.write(key), start, end);
			if (null == bresults || bresults.isEmpty()) return results;
			for (byte[] bresult : bresults) {
				results.add(SerializerUtils.read(bresult));
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return results;
	}
	
	/**
	 * SortedSet讀取成員和分數
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public List<Map.Entry<String, Double>> zrevrangeWithScores(String key, long start, long end) {
		List<Map.Entry<String, Double>> resultList = new ArrayList<Map.Entry<String, Double>>();
		try {
			Set<Tuple> tuples = jedisCluster.zrevrangeWithScores(SerializerUtils.write(key), start, end);
			if (null == tuples || tuples.isEmpty()) return resultList;
			Map<String, Double> results = new HashMap<String, Double>();
			for (Tuple tuple : tuples) {
				results.put(String.valueOf(SerializerUtils.read(tuple.getBinaryElement())), tuple.getScore());
			}
			resultList.addAll(results.entrySet());
			Collections.sort(resultList, new Comparator<Map.Entry<String, Double>>(){
				@Override
				public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
					return -o1.getValue().compareTo(o2.getValue());
				}
			});
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return resultList;
	}
	
	/**
	 * SORTEDSET數據集合長度
	 * @param key
	 * @return
	 */
	public long zcard(String key) {
		try {
			return jedisCluster.zcard(SerializerUtils.write(key));
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
	/**
	 * SortedSet移除成員
	 * @param key
	 * @param member
	 * @return
	 */
	public long zrem(String key, Object... members) {
		try {
			if (null == members|| members.length == 0) return 0;
			byte[][] bmembers = new byte[members.length][];
			for (int i = 0, len = members.length; i < len; i++) {
				bmembers[i] = SerializerUtils.write(members[i]);
			}
			return jedisCluster.zrem(SerializerUtils.write(key), bmembers);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return 0;
	}
	
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章