使用Jedis连接集群Redis(支持Redis复杂操作)

时间:2021-09-16 17:29:47

Jedis-2.7.2 版本虽然支持连接集群 Redis,但是仅仅支持 String 字符串的存储,并不支持 Map、Set、List,在这里分享一个能够支持复杂操作的方法。

import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisClusterCommand;
import redis.clients.jedis.JedisClusterConnectionHandler;
import redis.clients.jedis.JedisSlotBasedConnectionHandler;

public class BinaryJedisCluster {

private int maxRedirections;
private JedisClusterConnectionHandler connectionHandler;

public BinaryJedisCluster(Set<HostAndPort> nodes, int timeout, int maxRedirections) {
this(nodes, timeout, maxRedirections, new GenericObjectPoolConfig());
}

public BinaryJedisCluster(Set<HostAndPort> jedisClusterNode, int timeout, int maxRedirections,
final GenericObjectPoolConfig poolConfig) {
this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, timeout);
this.maxRedirections = maxRedirections;
}

public String set(final String key, final String value) {
return new JedisClusterCommand<String>(connectionHandler, maxRedirections) {

@Override
public String execute(Jedis connection) {
return connection.set(key, value);
}
}.run(key);
}

public String get(final String key) {
return new JedisClusterCommand<String>(connectionHandler, maxRedirections) {

@Override
public String execute(Jedis connection) {
return connection.get(key);
}
}.run(key);
}
}

(注:这是简化版的,具体代码并非原创,就不贴了。)

Map、Set、List 等类似 String,在 execute 方法中通过 Jedis 直接操作 Redis 即可。


在与 Spring 结合使用时,可以通过继承 InitializingBean 来实现初始化注入。

    private BinaryJedisCluster jc;

@Override
public void afterPropertiesSet() throws Exception {
Set<HostAndPort> set = new HashSet<HostAndPort>();
set.add(new HostAndPort(host,port));
...
jc = new BinaryJedisCluster(set, 5000, 6);
}