1. 程式人生 > >開啟運維之路之第 7 篇——RedisDesktopManager使用、Keys通用操作、Java程式碼操作基本的Redis

開啟運維之路之第 7 篇——RedisDesktopManager使用、Keys通用操作、Java程式碼操作基本的Redis

RedisDesktopManager下載地址:Redis桌面管理工具官方下載地址

安裝好,直接雙擊開啟。

說明:我本機的 IP 由於使用公司的 IP ,經常會變動,但不影響連線 Linux 虛擬機器。

現在發現個問題,無法連線到 Redis 。

解決過程:

①Redis 在預設情況下,配置檔案裡並沒有設定登入密碼,可以檢視:前提是先進入 Redis 客戶端,命令檢視上一篇部落格。

127.0.0.1:6379> config get requirepass
1) "requirepass"
2) ""

預設情況下 requirepass 引數是空的,這就意味著你無需通過密碼驗證就可以連線到 redis 服務。可問題是不用密碼也連線不上,這不是坑爹?

不,不多踩一些坑,是不會有進步的,特別是在技術領域。一帆風順反而引起你的恐慌。

那就設定一下登入 Redis 的密碼:config set requirepass XXXXX

127.0.0.1:6379> config set requirepass 123456
OK
127.0.0.1:6379> auth 123456
OK

說明:如果遇到下面的錯誤:(error) ERR Client sent AUTH, but no password is set

請先進入客戶端,設定如下命令:config set requirepass XXXXX,再進行授權密碼XXXXX

再驗證下:

還是不行。

想一下,應該是防火牆的問題。防火牆。防火牆。防火牆。

檢視防火牆狀態:

127.0.0.1:6379> exit
[[email protected] redis]# firewall-cmd --state
not running

結果防火牆也沒開啟,因為我已經設定防火牆開機不啟動了。(防火牆沒開啟,說明 Linux 的埠都可以訪問。以前聽說那些網站被病毒攻擊,就是因為病毒使用了某些開放的埠,讓病毒有機可乘。一般是不去訪問病毒網站或者關閉病毒入侵的埠號。)

OK,那就應該是配置檔案的問題了。去看下。(說明:本系列部落格,在玩 Redis 的時候,已經把配置檔案複製出來,放在與 Redis 解壓檔案的同一級目錄了。原生的 redis.conf 檔案並沒有改動。這樣一來,哪怕你玩壞了複製的那份配置檔案,也不會有問題,還可以使用原生的配置檔案。)

[[email protected] redis]# ls
bin  dump.rdb  redis.conf

下面是檢視原生 redis.conf 配置檔案的命令:

[[email protected] ~]# cd /root/redis-4.0.10
[[email protected] redis-4.0.10]# ls
00-RELEASENOTES  deps       README.md        runtest-sentinel  utils
BUGS             INSTALL    redis.conf       sentinel.conf
CONTRIBUTING     Makefile   runtest          src
COPYING          MANIFESTO  runtest-cluster  tests

OK,修改一下我們預設啟動時使用的配置檔案:我們之前複製了一份配置檔案放在 redis 的目錄下。

[[email protected] redis]# ls
bin  dump.rdb  redis.conf

現在修改這份配置檔案:[[email protected] redis]# vi redis.conf 

找到 bind 127.0.0.1,新增 # 註釋掉。不註釋掉就只有使用 Linux 機器才能登入。然後儲存退出。

這時候再連線,還是會報錯!因為沒有重啟。然後就重啟 Redis 。

可以使用 shell 指令碼,也可以敲打命令:

[[email protected] ~]# cd /usr/local/redis/
[[email protected] redis]# ./bin/redis-server ./redis.conf 

OK,windows客戶端管理連線成功!

這時候,我們再進入 Linux 下 Redis 的客戶端,ping 一下:

[[email protected] redis]# ./bin/redis-cli
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.

無法 ping 通,必須使用密碼。那就設定密碼。

127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> ping
PONG

說明:這樣設定授權密碼的方式,在重啟 Redis 之後,密碼失效,又得重新設定。因此,我們設定到 Redis 的配置檔案,下次啟動就不需要重新設定密碼了。

修改配置檔案:通過輸入 /requirepass 搜尋密碼設定,n 查詢下一個,N查詢上一個匹配的字串。

[[email protected] redis]# vi redis.conf

然後修改密碼:把註釋去掉,修改 foobared 成你的密碼。

儲存,退出。這樣,下次就不需要再重新授權密碼了。不過,進入 Redis 客戶端,都要通過密碼登陸。

[[email protected] redis]# ./bin/redis-cli
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> ping
PONG

還有一種方式,就是去掉 Redis 的自我保護,但這種方式安全性差,不推薦,只有在特殊的情況下使用,瞭解即可。

 

OK,回到windows的Redis管理工具

說明:Redis 預設使用 db0 這個庫。裡面存放著所有的資料,就是我們之前測試的。右邊主要是資料的一些操作。TTL (Time To Live)的值是 -1 說明資料不會過期。我們試著在這裡增加一些資料,然後去 Linux 客戶端下檢視:

注意,我們設定的是 hash 型別,需要根據 hash 的特性進行獲取值:

OK,完美搞定!

 

Keys通用操作

①顯示所有 keys ,包括 5 種資料型別:keys *

127.0.0.1:6379> keys *
 1) "s1"
 2) "myList3"
 3) "sr1"
 4) "n1"
 5) "h1"
 6) "c"
 7) "m"

②正則表示式: * 代表所有,? 代表一個字元

127.0.0.1:6379> keys s*
1) "s1"
2) "sr1"
3) "s2"
4) "sr2"
5) "sr3"
127.0.0.1:6379> keys s?
1) "s1"
2) "s2"

③刪除 key:del key1 key2  ...

127.0.0.1:6379> del n1 c
(integer) 2

④判斷 key 是否存在:1-存在,0-不存在:exists key

127.0.0.1:6379> exists n1
(integer) 0
127.0.0.1:6379> exists s1
(integer) 1

⑤對 key 重新命名:rename oldName newName

127.0.0.1:6379> rename m m2
OK

⑥設定 key 的有效期:expire key time  單位:秒

127.0.0.1:6379> expire m2 120
(integer) 1

我們開啟 Redis 桌面管理工具,檢視 m2 的有效期

⑦檢視 key 有效期:ttl key

127.0.0.1:6379> ttl m2
(integer) 4
127.0.0.1:6379> ttl m2
(integer) 1
127.0.0.1:6379> ttl m2
(integer) -2

說明:單位是秒,-1 是永久有效,-2 是已經不存在。

對不存在的 key 設定過期時間,返回 0 :

127.0.0.1:6379> expire m2 123
(integer) 0

⑧檢視 key 型別:type key

127.0.0.1:6379> type s1
set
127.0.0.1:6379> type n
string

 

Java程式碼操作基本的Redis

①在 pom.xml 配置檔案裡新增下面的配置

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

或者去下載一個操作 Redis 的 jar 包,地址:操作 Redis 的 jar 包下載地址

OK,編寫測試Java類:

package com.test.test;

import redis.clients.jedis.Jedis;

public class JedisTest {
    
    public static void main(String[] args){
        Jedis jedis=new Jedis();
    }

}

到這步,我們進入 Jedis 類,看下里面的構造器、實現的方法。按住 Ctrl + 滑鼠左鍵,進入 Jedis 類。

看下常用方法:(只列舉一點做引導,很多方法都是根據 Redis 客戶端的方法來定義方法名的。這樣可以避免方法名的轉換,顧名思義,即拿即用。)

/**
   * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1
   * GB).
   * <p>
   * Time complexity: O(1)
   * @param key
   * @param value
   * @return Status code reply
   */
  public String set(final String key, String value) {
    checkIsInMultiOrPipeline();
    client.set(key, value);
    return client.getStatusCodeReply();
  }

/**
   * Get the value of the specified key. If the key does not exist null is returned. If the value
   * stored at key is not a string an error is returned because GET can only handle string values.
   * <p>
   * Time complexity: O(1)
   * @param key
   * @return Bulk reply
   */
  public String get(final String key) {
    checkIsInMultiOrPipeline();
    client.sendCommand(Protocol.Command.GET, key);
    return client.getBulkReply();
  }

/**
   * Test if the specified key exists. The command returns "1" if the key exists, otherwise "0" is
   * returned. Note that even keys set with an empty string as value will return "1". Time
   * complexity: O(1)
   * @param key
   * @return Boolean reply, true if the key exists, otherwise false
   */
  public Boolean exists(final String key) {
    checkIsInMultiOrPipeline();
    client.exists(key);
    return client.getIntegerReply() == 1;
  }

public Long del(String key) {
    client.del(key);
    return client.getIntegerReply();
  }

public Long expire(final String key, final int seconds) {
    checkIsInMultiOrPipeline();
    client.expire(key, seconds);
    return client.getIntegerReply();
  }

public Long ttl(final String key) {
    checkIsInMultiOrPipeline();
    client.ttl(key);
    return client.getIntegerReply();
  }


public Long hset(final String key, final String field, final String value) {
    checkIsInMultiOrPipeline();
    client.hset(key, field, value);
    return client.getIntegerReply();
  }

public String hget(final String key, final String field) {
    checkIsInMultiOrPipeline();
    client.hget(key, field);
    return client.getBulkReply();
  }

OK,我們來玩一下:

public static void main(String[] args){
        Jedis jedis=new Jedis("192.168.126.130",6379);
        jedis.set("name","Hi,girl,would you love me? 好噠");
        String name=jedis.get("name");
        System.out.println("name="+name);
        jedis.close();
    }

點選執行 main 函式:

說明了啥?需要授權密碼。OK,我們設定密碼:

perfect!強勢搞定!不信去 Redis 桌面管理工具看看!

 

package com.test.test;

import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;

public class JedisTest {

    public static void main(String[] args){
        Jedis jedis=new Jedis("192.168.126.130",6379);
        jedis.auth("123456");

        /*************** 測試 string *******************/
        jedis.set("name","Hi,girl,would you love me? 好噠");
        String name=jedis.get("name");
        System.out.println("name="+name);

        /*************** 測試 list *******************/
        jedis.rpush("jList","What's your "," telephone ?");
        List<String> list= jedis.lrange("jList",0,-1);
        for(String str : list){
            System.out.println(str);
        }

        /*************** 測試 hash *******************/
        jedis.hset("jHash","hometown","My hometown is 流放深圳!");
        String hash=jedis.hget("jHash","hometown");
        System.out.println(hash);

        /*************** 測試 set *******************/
        jedis.sadd("jSet","北京");
        jedis.sadd("jSet","上海");
        jedis.sadd("jSet","深圳");
        Set<String> set = jedis.smembers("jSet");
        for(String str : set) {
            System.out.println(str);
        }

        /*************** 測試 zset *******************/
        jedis.zadd("jzSet",18,"小薇");
        jedis.zadd("jzSet",20,"小胖");
        jedis.zadd("jzSet",15,"小傻");
        Set<String> zset=jedis.zrange("jzSet",0,-1);
        for(String str : zset){
            System.out.println(str);
        }
        jedis.close();
    }

}