Java jedis 哨兵、集群

  1. 引入相关依赖:
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
  1. redis.properties
redis.host=localhost
redis.password=

redis.port=6379
redis.timeout=1000

redis.pool.maxTotal=100
redis.pool.maxIdle=100
redis.pool.minIdle=50
redis.pool.maxWaitMillis=10000
redis.pool.testOnBorrow=false
redis.pool.testOnReturn=false
redis.pool.testWhileIdle=true
  1. @Bean
@Configuration
@PropertySource(name = "redis.properties", value = "classpath:redis.properties", ignoreResourceNotFound = false)
public class RedisConfiguration {

	@Value("${redis.host}")
	private String host;

	@Value("${redis.port}")
	private Integer port;

	@Value("${redis.password}")
	private String password;

	@Value("${redis.timeout}")
	private Integer timeout;

	@Value("${redis.pool.maxTotal}")
	private Integer maxTotal;

	@Value("${redis.pool.maxIdle}")
	private Integer maxIdle;

	@Value("${redis.pool.minIdle}")
	private Integer minIdle;

	@Value("${redis.pool.maxWaitMillis}")
	private int maxWaitMillis;

	@Value("${redis.pool.testOnBorrow}")
	private boolean testOnBorrow;

	@Value("${redis.pool.testOnReturn}")
	private boolean testOnReturn;

	@Value("${redis.pool.testWhileIdle}")
	private boolean testWhileIdle;

	//基础
	@Bean
	public JedisPool jedisPool() {
		JedisPool jedisPool = null;
		if (password == null || "".equals(password) || "null".equalsIgnoreCase(password)) {
			jedisPool = new JedisPool(this.jedisPoolConfig(), host, port, timeout);
		} else {
			jedisPool = new JedisPool(this.jedisPoolConfig(), host, port, timeout, password);
		}
		return jedisPool;
	}

	//哨兵
	@Bean
	public JedisSentinelPool jedisSentinelPool() {
		Set<String> sentinels = new HashSet<>();
		sentinels.add(new HostAndPort(host1,port1).toString());
		sentinels.add(new HostAndPort(host2,port2).toString());
		sentinels.add(new HostAndPort(host3,port3).toString());
		//JedisSentinelPool其实本质跟JedisPool类似,都是与redis主节点建立的连接池
		//JedisSentinelPool并不是说与sentinel建立的连接池,而是通过sentinel发现redis主节点并与其建立连接
		JedisSentinelPool jedisSentinelPool = null;
		String masterName = mymaster;
		if (password == null || "".equals(password) || "null".equalsIgnoreCase(password)) {
			jedisSentinelPool = new JedisSentinelPool(masterName, sentinels, this.jedisPoolConfig(), port);
		}else{
			jedisSentinelPool = new JedisSentinelPool(masterName, sentinels, this.jedisPoolConfig(), port, password);
		}
		return jedisSentinelPool;
	}

	//集群
	@Bean
	public JedisCluster jedisCluster() {
		Set<HostAndPort> jedisClusterNodeSet = new HashSet<>();
		jedisClusterNodeSet.add(new HostAndPort(host1, port1));
		jedisClusterNodeSet.add(new HostAndPort(host2, port2));
		jedisClusterNodeSet.add(new HostAndPort(host3, port3));
		jedisClusterNodeSet.add(new HostAndPort(host4, port4));
		jedisClusterNodeSet.add(new HostAndPort(host5, port5));
		jedisClusterNodeSet.add(new HostAndPort(host6, port6));

		JedisCluster jedisCluster = null;
		//int connectionTimeout 连接时间, int soTimeout 返回时间, int maxAttempts 连接重试次数
		if (password == null || "".equals(password) || "null".equalsIgnoreCase(password)) {
			jedisCluster = new JedisCluster(jedisClusterNodeSet, 6000, 5000, 10, this.jedisPoolConfig());
		} else {
			jedisCluster = new JedisCluster(jedisClusterNodeSet, 6000, 5000, 10, password, this.jedisPoolConfig());
		}
		return jedisCluster;
	}

	private JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(this.maxTotal);
		jedisPoolConfig.setMaxIdle(this.maxIdle);
		jedisPoolConfig.setMinIdle(this.minIdle);
		jedisPoolConfig.setMaxWaitMillis(this.maxWaitMillis);
		jedisPoolConfig.setTestOnBorrow(this.testOnBorrow);
		jedisPoolConfig.setTestOnReturn(this.testOnReturn);
		jedisPoolConfig.setTestWhileIdle(this.testWhileIdle);
		return jedisPoolConfig;
	}

	@Bean
	@Scope("prototype")
	public RedisUtil redisUtil() {
		return new RedisUtil();
	}
}

  1. RedisUtil
@Slf4j
@Component
public final class RedisUtil {

	@Autowired
	private JedisPool jedisPool;

	private String regionName;

	private Integer index;

	public String getRegionName() {
		return regionName;
	}

	public void setRegionName(String regionName) {
		this.index = RedisConstant.dbIndexMap.get(regionName);
		this.regionName = regionName;
	}

	public Integer getIndex() {
		return index;
	}

	public void setIndex(Integer index) {
		this.index = index;
	}

	private Jedis getJedis() {
		try {
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				if (index != null) {
					resource.select(index);
				}
				return resource;
			} else {
				log.info("未获取到Redis连接");
				return null;
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	@SuppressWarnings("deprecation")
	private void returnResource(Jedis jedis) {
		if (jedis != null) {
			jedisPool.returnResource(jedis);
		} else {
			log.warn("jedisPool is null ...");
		}
	}

	@SuppressWarnings("deprecation")
	private void returnBrokenResource(Jedis jedis) {
		if (jedis != null) {
			jedisPool.returnBrokenResource(jedis);
		} else {
			log.warn("jedisPool is null ...");
		}
	}

	public RedisUtil() {
		super();
	}

	public RedisUtil(String regionName, Integer index) {
		super();
		this.regionName = regionName;
		this.index = index;
	}

	public RedisUtil(String regionName) {
		super();
		this.regionName = regionName;
		this.index = RedisConstant.dbIndexMap.get(regionName) + RedisConstant.dbBeginIndex;
	}

	public boolean set(String key, Object value) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			String result = jedis.set(redisKey, redisValue);
			return "OK".equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean set(String key, Object value, long expireTime) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			String result = jedis.set(redisKey, redisValue, "NX", "EX", expireTime);
			return "OK".equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long setByPipeline(Map<String, String> map) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			for (Entry<String, String> entry : map.entrySet()) {
				pipeline.set(strategyKey(entry.getKey()), entry.getValue());
			}
			pipeline.sync();
			return (long) map.size();
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean saddByPipeline(String key, Set<String> set) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			for (String value : set) {
				pipeline.sadd(strategyKey(key), value);
			}
			pipeline.sync();
			return true;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public void setByPipelineArray(Map<String, String[]> map) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			for (Entry<String, String[]> entry : map.entrySet()) {
				pipeline.sadd(strategyKey(entry.getKey()), entry.getValue());
			}
			pipeline.sync();
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public String get(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.get(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Map<String, Map<String, String>> getByPipeline(String... keys) throws Exception {
		Map<String, Response<Map<String, String>>> responses = new HashMap<String, Response<Map<String, String>>>(
				keys.length);
		Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			for (String key : keys) {
				key = strategyKey(key);
				responses.put(key, pipeline.hgetAll(key));
			}
			pipeline.sync();
			for (Entry<String, Response<Map<String, String>>> entry : responses.entrySet()) {
				map.put(entry.getKey(), entry.getValue().get());
			}
			return map;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public List<String> mget(String... keys) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String[] redisKeys = new String[keys.length];
			for (int i = 0; i < keys.length; i++) {
				redisKeys[i] = strategyKey(keys[i]);
			}
			return jedis.mget(redisKeys);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public List<String> mgetByPipeline(String... keys) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			String[] redisKeys = new String[keys.length];
			for (int i = 0; i < keys.length; i++) {
				redisKeys[i] = strategyKey(keys[i]);
			}
			Response<List<String>> response = pipeline.mget(redisKeys);
			pipeline.sync();
			return response.get();
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean setex(String key, Object value, int seconds) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			String result = jedis.setex(redisKey, seconds, redisValue);
			return "OK".equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean setnx(String key, Object value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			Long result = jedis.setnx(redisKey, redisValue);
			return new Long(1L).equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long del(String... keys) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKeys[] = new String[keys.length];
			for (int i = 0; i < keys.length; i++) {
				redisKeys[i] = strategyKey(keys[i]);
			}
			return jedis.del(redisKeys);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean delNX(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			if (jedis == null) {
				return false;
			}
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			List<String> keyList = new ArrayList<String>(1);
			keyList.add(redisKey);
			List<String> argList = new ArrayList<String>(1);
			argList.add(redisValue);
			String checkAndDelScript = "if redis.call('get', KEYS[1]) == ARGV[1] then "
					+ "return redis.call('del', KEYS[1]) " + "else " + "return 0 " + "end";
			Object result = jedis.eval(checkAndDelScript, keyList, argList);
			return "1".equals(result.toString()) ? true : false;
		} catch (Exception ex) {
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return false;
	}

	public boolean exists(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.exists(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean expire(String key, int seconds) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			Long result = jedis.expire(redisKey, seconds);
			return new Long(1L).equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long lpush(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.lpush(redisKey, value);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long lpush(String key, String... value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.lpush(redisKey, value);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long rpush(String key, Object value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			return jedis.rpush(redisKey, redisValue);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public String lpop(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.lpop(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public String rpop(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.rpop(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long llen(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.llen(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long lrem(String key, Long count, Object value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			return jedis.lrem(redisKey, count, redisValue);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public List<String> lrange(String key, Long start, Long end) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.lrange(redisKey, start, end);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public String getSet(String key, Object value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			return jedis.getSet(redisKey, redisValue);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long ttl(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.ttl(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean rename(String oldkey, String newkey) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String oldRedisKey = strategyKey(oldkey);
			String newRedisKey = strategyKey(newkey);
			String result = jedis.rename(oldRedisKey, newRedisKey);
			return "OK".equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean renamenx(String oldkey, String newkey) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String oldRedisKey = strategyKey(oldkey);
			String newRedisKey = strategyKey(newkey);
			Long result = jedis.renamenx(oldRedisKey, newRedisKey);
			return new Long(1L).equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean hset(String key, String field, Object value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			Long result = jedis.hset(redisKey, field, redisValue);
			return new Long(1L).equals(result);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public String hget(String key, String field) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.hget(redisKey, field);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Map<String, String> hgetByPipeline(String key, String... fields) {
		Jedis jedis = null;
		Map<String, Response<String>> responseMap = null;
		Map<String, String> resultMap = null;
		try {
			jedis = getJedis();
			Pipeline pipelined = jedis.pipelined();
			String redisKey = strategyKey(key);
			responseMap = new HashMap<String, Response<String>>();
			for (int i = 0; i < fields.length; i++) {
				responseMap.put(fields[i], pipelined.hget(redisKey, fields[i]));
			}
			pipelined.sync();
			resultMap = new HashMap<String, String>();
			for (Entry<String, Response<String>> entry : responseMap.entrySet()) {
				resultMap.put(entry.getKey(), entry.getValue().get());
			}
			return resultMap;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Map<String, String> hget(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.hgetAll(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Map<String, List<String>> hmget(String[] keys, String... fields) {
		Jedis jedis = null;
		Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
		try {
			jedis = getJedis();
			String[] redisKeys = new String[keys.length];
			for (int i = 0; i < keys.length; i++) {
				redisKeys[i] = strategyKey(keys[i]);
				map.put(keys[i], jedis.hmget(redisKeys[i], fields));
			}
			return map;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	/**
	 * 批量设置Hash的属性
	 * 
	 * @param key
	 * @param map Map<String, String>
	 * @return
	 */
	public boolean hmset(String key, Map<String, String> map) {
		if ((key == null || "".equals(key) || "null".equals(key)) || 0 == map.size()) {
			return false;
		}
		Jedis jedis = getJedis();
		key = strategyKey(key);
		String statusCode = jedis.hmset(key, map);
		jedis.close();
		if ("OK".equalsIgnoreCase(statusCode)) {
			return true;
		}
		return false;
	}

	public Map<String, List<String>> hmgetByPipeline(String... keys) throws Exception {
		Map<String, Response<List<String>>> responses = new HashMap<String, Response<List<String>>>(keys.length);
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			for (String key : keys) {
				key = strategyKey(key);
				responses.put(key, pipeline.hmget(key));
			}
			pipeline.sync();
			for (Entry<String, Response<List<String>>> entry : responses.entrySet()) {
				map.put(entry.getKey().substring(entry.getKey().lastIndexOf("_") + 1, entry.getKey().length()),
						entry.getValue().get());
			}
			return map;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long hdel(String key, String... fields) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.hdel(redisKey, fields);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public boolean hexists(String key, String field) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.hexists(redisKey, field);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Set<String> hkeys(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.hkeys(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long hlen(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.hlen(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long hsetnx(String key, String field, Object value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			String redisValue = strategyValue(value);
			return jedis.hsetnx(redisKey, field, redisValue);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Map<String, List<String>> hvals(String... keys) {
		Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = "";
			for (int i = 0; i < keys.length; i++) {
				redisKey = strategyKey(keys[i]);
				map.put(keys[i], jedis.hvals(redisKey));
			}
			return map;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Map<String, List<String>> hvalsByPipeline(String... keys) throws Exception {
		Map<String, Response<List<String>>> responses = new HashMap<String, Response<List<String>>>(keys.length);
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			for (String key : keys) {
				key = strategyKey(key);
				responses.put(key, pipeline.hvals(key));
			}
			pipeline.sync();
			for (Entry<String, Response<List<String>>> entry : responses.entrySet()) {
				map.put(entry.getKey().substring(entry.getKey().lastIndexOf("_") + 1, entry.getKey().length()),
						entry.getValue().get());
			}
			return map;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	/**
	 * 
	 * @Title: hvalsByPipelineIndex
	 * @Description: hvalsByPipelineIndex()
	 * @param @param  keys
	 * @param @return
	 * @param @throws Exception 设定文件
	 * @return Map<String,List<String>> 返回类型
	 * @throws @author Comsys-zhangq
	 */
	public Map<String, Map<String, String>> hvalsByPipelineByRisk(String... keys) throws Exception {

		Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
		Jedis jedis = null;

		try {

			jedis = getJedis();
			for (String key : keys) {
				key = strategyKey(key);
				map.put(key.substring((RedisConstant.KEY_SEPERATOR).length(), key.length()),
						(Map<String, String>) jedis.hgetAll(key));

			}
			return map;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Boolean sadd(String key, String... members) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.sadd(redisKey, members) == members.length ? true : false;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Set<String> sdiff(String... keys) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKeys[] = new String[keys.length];
			for (int i = 0; i < keys.length; i++) {
				redisKeys[i] = strategyKey(keys[i]);
			}
			return jedis.sdiff(redisKeys);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public String spop(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.spop(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long scard(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.scard(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Set<String> smembers(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			Set<String> set = new HashSet<>();
			Set<String> smembers = jedis.smembers(redisKey);
			set.addAll(smembers);
			return set;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Set<String> sinter(String... keys) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKeys[] = new String[keys.length];
			for (int i = 0; i < keys.length; i++) {
				redisKeys[i] = strategyKey(keys[i]);
			}
			return jedis.sinter(redisKeys);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Boolean srem(String key, String... members) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.srem(redisKey, members) == members.length ? true : false;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public String type(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.type(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long strlen(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.strlen(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long incr(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.incr(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long decr(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.decr(redisKey);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long incrBy(String key, Long count) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.incrBy(redisKey, count);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long decrBy(String key, Long count) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.decrBy(redisKey, count);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long hincrBy(String key, String field, Long count) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String redisKey = strategyKey(key);
			return jedis.hincrBy(redisKey, field, count);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	private String strategyKey(String key) {
		if (regionName == null || "".equals(regionName) || "null".equals(regionName)) {
			regionName = "default";
		}
		return regionName + "_" + key;
	}

	private String strategyValue(Object value) {
		String result = null;
		if (value != null) {
			if (value instanceof String) {
				result = value.toString();
			} else if (value instanceof Integer) {
				result = value.toString();
			} else if (value instanceof Long) {
				result = value.toString();
			} else if (value instanceof Double) {
				result = value.toString();
			} else if (value instanceof Float) {
				result = value.toString();
			} else if (value.getClass() == int.class) {
				result = value.toString();
			} else if (value.getClass() == long.class) {
				result = value.toString();
			} else if (value.getClass() == double.class) {
				result = value.toString();
			} else if (value.getClass() == float.class) {
				result = value.toString();
			} else {
				result = JSON.toJSONString(value);
			}
		}
		return result;
	}

	public List<Map<String, String>> sentinelMasters(String key) {

		Jedis jedis = null;
		try {
			jedis = getJedis();
			@SuppressWarnings("unused")
			String redisKey = strategyKey(key);
			return jedis.sentinelMasters();
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}

	}

	public Long hsetByPipeline(String key, Map<String, String> fieldValues) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			key = strategyKey(key);
			for (Entry<String, String> entry : fieldValues.entrySet()) {
				pipeline.hset(key, entry.getKey(), entry.getValue());
			}
			pipeline.sync();
			return (long) fieldValues.size();
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Long deleteByPipeline(String... keys) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipeline = jedis.pipelined();
			String redisKeys[] = new String[keys.length];
			for (int i = 0; i < keys.length; i++) {
				redisKeys[i] = strategyKey(keys[i]);
			}
			pipeline.del(redisKeys);
			pipeline.sync();
			return (long) keys.length;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	/**
	 * 判断当前值是否在key对应的set中存在
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public Boolean sisMember(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			key = strategyKey(key);
			return jedis.sismember(key, value);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Map<String, String> hgetall(String key) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			key = strategyKey(key);
			return jedis.hgetAll(key);
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Boolean publish(String channel, String message) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Long publish = jedis.publish(channel, message);
			return publish == 1 ? true : false;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

	public Boolean publishByPipeline(String channel, List<String> messageList) throws Exception {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Pipeline pipelined = jedis.pipelined();
			for (int i = 0; i < messageList.size(); i++) {
				pipelined.publish(channel, messageList.get(i));
			}
			pipelined.sync();
			return true;
		} catch (Exception e) {
			returnBrokenResource(jedis);
			log.error(e.getMessage(), e);
			throw new RedisException(e);
		} finally {
			returnResource(jedis);
		}
	}

}

SpringBoot 哨兵、集群

Spring Boot整合Redis连接代码
  1. 依赖
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-pool2</artifactId>
</dependency>
  1. 配置
server:
  port: 8080

spring:
  redis:
    database: 0
    timeout: 3000
    sentinel:    #哨兵模式
      master: mymaster #主服务器所在集群名称
    cluster:    #集群
	    nodes: 192.168.0.60:26379,192.168.0.60:26380,192.168.0.60:26381
    lettuce:
      pool:
        max-idle: 50
        min-idle: 10
        max-active: 100
        max-wait: 1000
  1. 使用
@Autowired
private StringRedisTemplate stringRedisTemplate;

stringRedisTemplate.opsForValue().set("test", "ok");
StringRedisTemplate与RedisTemplate详解

spring 封装了 RedisTemplate 对象来进行对redis的各种操作,它支持所有的 redis 原生的 api。在RedisTemplate中提供了几个常用的接口方法的使用,分别是:

private ValueOperations<K, V> valueOps;
private HashOperations<K, V> hashOps;
private ListOperations<K, V> listOps;
private SetOperations<K, V> setOps;
private ZSetOperations<K, V> zSetOps;

RedisTemplate中定义了对5种数据结构操作

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

StringRedisTemplate继承自RedisTemplate,也一样拥有上面这些操作。
StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。
RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐