1. 程式人生 > >使用Jedis連線叢集Redis(支援Redis複雜操作)

使用Jedis連線叢集Redis(支援Redis複雜操作)

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);
    }