【redis相關】Linux下配置Redis環境

1、安裝和部署redis

這裏用的是Ubuntu的linux虛擬機安裝配置redis4.0.14

首先在官網下載redis壓縮包 官網地址

下載後進入linux系統,將壓縮包放到要安裝的目錄下,我這裏放在了/usr/local/redis中

解壓redis壓縮包

解壓完成後,首先確認你的linux有沒有安裝gcc編譯器,如果沒有,先安裝gcc。如果使用的是Centos就直接使用yum命令來安裝gcc,我這裏用的是Ubuntu,所以使用以下命令

sudo apt-get install -y gcc

安裝好後如下圖顯示

然後進入到剛纔解壓過後的redis目錄中,執行以下命令:

make MALLOC=libc

等待redis安裝完成,完成後如下圖所示:

安裝完成後,進入redis安裝目錄下的src文件夾

可以看到其中有兩個文件redis-server和redis-cli

首先我們啓動redis,執行./redis-server命令,成功啓動後如下圖:

可以看到端口號爲6379也就是說我們後面訪問redis要通過6379端口。

接下來進行簡單的測試,在redis目錄下啓動redis-cli,輸入set “key” “value”存入數據,再輸入get “key”取得數據。

2、Java操作redis

創建一個maven項目,添加jedis依賴。

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

在Linux虛擬機中啓動redis,測試項目中創建測試類如下:

public class RedisTest {
    public static void main(String[] args) {
        //連接本地的 Redis 服務
        Jedis jedis = new Jedis("10.211.55.5");
        //設置 redis 字符串數據
        jedis.set("key02", "banana");
        // 獲取存儲的數據並輸出
        System.out.println("redis 存儲的字符串爲: "+ jedis.get("key02"));
    }
}

運行程序,報錯:

objc[15063]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin/java (0x10412e4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1061c04e0). One of the two will be used. Which one is undefined.
Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

內容是說訪問redis服務失敗,因爲開啓了保護模式,綁定了訪問地址,也給出了幾個解決辦法。

打開redis的配置文件

內容如下,其中有兩項配置需要修改,一個是bind 127.0.0.0 表示redis只接受本地請求的訪問,這裏將bind註釋掉

另一項就是protected-mode yes表示開啓保護模式,這裏將它關掉,yes改爲no,保存並關閉。

按下command+c,輸入./redis-server ../redis.conf 重啓redis並啓用配置,啓動測試程序進行測試,結果如下

 

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