連接Redis集群


1.配置集群設置

 https://www.cnblogs.com/9080dlb/p/15729558.html

2.導包

    <dependency>
         <groupId>redis.clients</groupId>
         <artifactId>jedis</artifactId>
         <version>3.6.3</version>
     </dependency>

3工具類

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;

import java.util.HashSet;
//集群配置
public class RedisClusterUtils {

    //集群密碼
    private static String AUTH = "xxxxxx";

    private static JedisCluster jedisCluster = null;

    static {
        /**
         * 2.9.0及以后的jar包中,沒有setMaxActive和setMaxWait屬性了
         * maxActive----maxTotal
         * maxWait---maxWaitMillis
         */
        //池配置
        GenericObjectPoolConfig<Jedis> poolConfig = new GenericObjectPoolConfig<Jedis>();
        //最大連接數, 默認8個,賦值為-1 則表示不受限制
        //如果連接數為設置的值,此時狀態為exhausted耗盡
        poolConfig.setMaxTotal(1000);
        //最大空閑連接數, 默認8個,控制空閑狀態數量,最多為設置的值
        poolConfig.setMaxIdle(50);
        //獲取連接時的最大等待毫秒數(如果設置為阻塞時BlockWhenExhausted)
        // 如果超時就拋異常, 小於零:阻塞不確定的時間,  默認-1永不超時
        poolConfig.setMaxWaitMillis(1000);
        //在獲取連接的時候檢查有效性, 默認false
        poolConfig.setTestWhileIdle(true);
        //在用一個redis實例時,是否提前進行驗證操作
        //如果為TRUE,則得到的實例都是可用的
        poolConfig.setTestOnBorrow(true);
        //是否進行有效性檢查
        poolConfig.setTestOnReturn(true);

        //節點信息
        HashSet<HostAndPort> set = new HashSet<HostAndPort>();
        set.add(new HostAndPort("4x.xx.xx.xx", 6379));//1-m
        set.add(new HostAndPort("4x.xxx.xx.xx", 6380));//1-s
        set.add(new HostAndPort("4x.xx.xx.xx",6379));//l-m
        set.add(new HostAndPort("4x.x.xxx.xx",6380));//l-s
        set.add(new HostAndPort("4x.xx.xx.xx",6379));//d-m
        set.add(new HostAndPort("4x.xx.xx.xx",6380));//d-s
        /**
         * 參數1 redis節點信息
         * 參數2 連接超時
         * 參數3 讀寫超時
         * 參數4 重試次數
         * 參數5 集群密碼
         * 參數6 連接池參數
         */
        jedisCluster = new JedisCluster(set, 5000, 5000, 5, AUTH, poolConfig);
        /**
         * 重試次數,JedisCluster在連接的時候,如果出現連接錯誤,則會嘗試隨機連接一個節點,
         * 如果當期嘗試的節點返回Moved重定向,jedis cluster會重新更新clots緩存。
         * 如果重試依然返回連接錯誤,會接着再次重試,
         * 當重試次數大於maxAttempts會報出
         * Jedis ClusterMaxRedirectionsException(“to many Cluster redireciotns?”)異常
         */
    }

    /**
     *
     * @return
     */
    public static JedisCluster getJRedis(){
        if (jedisCluster!=null){
            return jedisCluster;
        }
        return null;
    }
}

4.測試

 public static void main(String[] args) {
        JedisCluster jedis = RedisClusterUtils.getJRedis();
        if (jedis!=null){
            System.out.println("正常");
            jedis.set("user","張三");
            System.out.println("user = " + jedis.get("user"));
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM