jedis访问集群

package com.zhongan.test.kingbao_shanyin;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

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

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

public class ShanYinJedis {
    private static JedisSentinelPool pool =null;
    static{
        String sentryHosts ="10.253.10.152:27379,10.253.9.90:27379,10.253.101.135:27379,10.253.8.14:27379,10.139.102.143:27379";
        String masterName="master_1004_1";
        String password="jrhx_j3lut02c9b";
        
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(1);
        poolConfig.setMaxTotal(1);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(false);
        String[] hostArray = sentryHosts.split(",");
        Set<String> hosts = new HashSet<>(Arrays.asList(hostArray));
        pool = new JedisSentinelPool(masterName, hosts, poolConfig, 5000, password);
    }
    /**
     * 分布式缓存(不带超时)
     * 
     * @param key key
     * @param value value
     */
    public static boolean set(String key, String value) {
        Jedis jedis = pool.getResource();
        try {
            jedis.set(key, value);
            return true;
        } catch (Exception e) {
            System.out.println("set value of key {} error"+key+e);
            return false;
        } finally {
            jedis.close();
        }

    }

    /**
     * 获取缓存key对应的值
     * 
     * @param key key
     * @return value
     */
    public static String get(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.get(key);
        } catch (Exception e) {
            System.out.println("get value of key {} error"+key+e);
            return null;
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public static Long del(String key) {
        Jedis jedis = pool.getResource();
        try {
            Long result = jedis.del(key);
            return result;
        } catch (Exception e) {
            System.out.println("del value of key {} error"+key+e);
            return null;
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }
    public static void main(String[] args) {
        String keyvalue = get("SY3C#loan#fengerliang#hct022e30a5ba06450c8");
        System.out.println(keyvalue);
        
//        Long del = del("SY3C#loan#fengerliang#hct022e30a5ba06450c8");
//        System.out.println(del);
    }

}
原文地址:https://www.cnblogs.com/HCT118/p/8440954.html