Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Redis 安裝與 Java 客戶端連線實作筆記

一、在 Linux 上安裝 Redis

解壓、編譯、啟動,一氣呵成:

tar xzf redis-2.4.6.tar
cd redis-2.4.6
make
nohup src/redis-server &

以下是更詳細的分解步驟:

步驟一:下載 Redis

步驟二:編譯原始碼

[root@localhost 4setup]# ll
總計 29168
-rw-r--r--1 root root 455240 2011-07-22 redis-2.2.12.tar.gz

[root@localhost 4setup]# tar xzf redis-2.2.12.tar.gz
[root@localhost 4setup]# cd redis-2.2.12
[root@localhost redis-2.2.12]# make
cd src && make all

步驟三:啟動 Redis 服務

[root@localhost redis-2.2.12]# src/redis-server
[6246] 05 Aug 19:17:22 # Warning: no config file specified, using the default config.
[6246] 05 Aug 19:17:22 * Server started, Redis version 2.2.12
[6246] 05 Aug 19:17:22 # WARNING overcommit_memory is set to 0!
[6246] 05 Aug 19:17:22 * The server is now ready to accept connections on port 6379

服務端預設埠號是 6379。另外那則 overcommit_memory 警告值得處理:把 vm.overcommit_memory = 1 寫進 /etc/sysctl.conf 後重開,或執行 sysctl vm.overcommit_memory=1 使其生效,可避免記憶體吃緊時背景存檔失敗。

步驟四:設為開機自啟

vi /etc/rc.local
# 加入一行:
/root/4setup/redis-2.2.12/src/redis-server

步驟五:客戶端連線驗證

另開一個工作階段執行:

[root@localhost redis-2.2.12]# src/redis-cli
redis 127.0.0.1:6379>

看到這個提示符就代表連線成功,可以開始操作了。

步驟六:查看 Redis 日誌

[6246] 05 Aug 19:24:33 - 0 clients connected (0 slaves), 539544 bytes in use
[6246] 05 Aug 19:24:37 - Accepted 127.0.0.1:51381
[6246] 05 Aug 19:24:38 - 1 clients connected (0 slaves), 547372 bytes in use

服務端的輸出就是最即時的運行狀況,連線數、記憶體用量、新連線來源都一目了然。

步驟七:停止 Redis

最簡單是在啟動它的工作階段按 Ctrl-C;也可以用客戶端的 shutdown 指令:

src/redis-cli shutdown

二、以 Java 客戶端訪問

在 Eclipse 中新建 Java 專案,把 Jedis 的 jar 匯入後,最小範例如下:

public static void main(String[] args) {
    Jedis jedis = new Jedis("147.151.240.234", 6379);
    jedis.set("foo", "bar");
    String value = jedis.get("foo");
    System.out.println(value);
}

執行後應在主控台印出 bar。若連不上,優先檢查三件事:Redis 是否仍在執行、防火牆是否放行 6379、以及 redis.conf 中的 bind 位址是否限制了來源。實務上要提醒的是,Redis 預設沒有密碼保護,對外開放前務必設定 requirepass,否則等於把資料庫門戶大開。

Copyright © Linux教程網 All Rights Reserved