本地java鏈接遠程服務器Linux上redis出錯解決方案

在redis.conf文件中bind 127.0.0.1加上#號
在redis.conf文件中把 #requirepass 的#號去掉,在後面加上鍊接redis-server的密碼
在redis.conf文件中bind 127.0.0.1加上#號

在redis.conf文件中把  #requirepass  的#號去掉,在後面加上鍊接redis-server的密碼

在本地用java代碼鏈接:

//Redis服務器IP
     private static String ADDR = "你的服務器ip";

     //Redis的端口號
     private static int PORT = 6379;

     //訪問密碼
     private static String AUTH = "你配置的redis密碼";

     //可用連接實例的最大數目,默認值爲8;
     //如果賦值爲-1,則表示不限制;如果pool已經分配了maxActive個jedis實例,則此時pool的狀態爲exhausted(耗盡)。
     private static int MAX_ACTIVE = 1024;

     //控制一個pool最多有多少個狀態爲idle(空閒的)的jedis實例,默認值也是8。
     private static int MAX_IDLE = 200;

     //等待可用連接的最大時間,單位毫秒,默認值爲-1,表示永不超時。如果超過等待時間,則直接拋出JedisConnectionException;
     private static int MAX_WAIT = 10000;

     private static int TIMEOUT = 10000;

     //在borrow一個jedis實例時,是否提前進行validate操作;如果爲true,則得到的jedis實例均是可用的;
     private static boolean TEST_ON_BORROW = true;

     private static JedisPool jedisPool = null;

    /**
      * 初始化Redis連接池
      */
     static {
         try {
             JedisPoolConfig config = new JedisPoolConfig();
             config.setMaxActive(MAX_ACTIVE);
             config.setMaxIdle(MAX_IDLE);
             config.setMaxWait(MAX_WAIT);
             config.setTestOnBorrow(TEST_ON_BORROW);
             jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
         } catch (Exception e) {
             e.printStackTrace();
         }
     }

     /**
      * 獲取Jedis實例
      * @return
      */
     public synchronized static Jedis getJedis() {
         try {
             if (jedisPool != null) {
                 Jedis resource = jedisPool.getResource();
                 return resource;
             } else {
                 return null;
             }
         } catch (Exception e) {
             e.printStackTrace();
             return null;
         }
     }

     /**
      * 釋放jedis資源
      * @param jedis
      */
         public static void returnResource(final Jedis jedis) {
             if (jedis != null) {
                 jedisPool.returnResource(jedis);
             }
         }

測試鏈接:

Jedis jedis = RedisUtil.getJedis();
        if(jedis.isConnected()){
            System.out.println("連接成功");
        }else{
            System.out.println("鏈接失敗");
        }

        //jedis.set("str1", "麼麼噠");            //存儲數據
       System.out.println(jedis.get("str1"));    //取出數據

控制檯:
控制檯輸出

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章