筆記:後端 - Redis

阿賀呀發表於2018-09-17

Redis學習

最近在向node後臺開發看齊,所以瞭解了一些關於redis的知識,這裡作為筆記

  • 安裝redis

    使用home-brew

    brew install redis

成功的提示資訊

To have launchd start redis at login: 
ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents 
Then to load redis now: 
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist 
Or, if you don’t want/need launchctl, you can just run: 
redis-server /usr/local/etc/redis.conf
複製程式碼

使用cat命令檢視配置資訊

cat /usr/local/etc/redis.conf

其中指定了埠等資訊

bind 127.0.0.1 ::1
bind 127.0.0.1
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 300
...
複製程式碼
  • 啟動redis redis-server /usr/local/etc/redis.conf 終端輸出
    9400:C 17 Sep 21:51:36.794 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
      9400:C 17 Sep 21:51:36.795 # Redis version=4.0.11, bits=64, commit=00000000, modified=0, pid=9400, just started
      9400:C 17 Sep 21:51:36.795 # Configuration loaded
      9400:M 17 Sep 21:51:36.796 * Increased maximum number of open files to 10032 (it was originally set to 7168).
                      _._
                 _.-``__ ''-._
            _.-``    `.  `_.  ''-._           Redis 4.0.11 (00000000/0) 64 bit
        .-`` .-```.  ```\/    _.,_ ''-._
       (    '      ,       .-`  | `,    )     Running in standalone mode
       |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
       |    `-._   `._    /     _.-'    |     PID: 9400
        `-._    `-._  `-./  _.-'    _.-'
       |`-._`-._    `-.__.-'    _.-'_.-'|
       |    `-._`-._        _.-'_.-'    |           http://redis.io
        `-._    `-._`-.__.-'_.-'    _.-'
       |`-._`-._    `-.__.-'    _.-'_.-'|
       |    `-._`-._        _.-'_.-'    |
        `-._    `-._`-.__.-'_.-'    _.-'
            `-._    `-.__.-'    _.-'
                `-._        _.-'
                    `-.__.-'
      
      9400:M 17 Sep 21:51:36.799 # Server initialized
      9400:M 17 Sep 21:51:36.800 * DB loaded from disk: 0.001 seconds
      9400:M 17 Sep 21:51:36.800 * Ready to accept connections
複製程式碼

這裡可以看到redis啟動成功,監聽的埠是6379 新開一個tab視窗 輸入redis-cli ping 可以看到控制檯輸出PONG 這就說明redis啟動成功

  • 關閉redis
    • 在啟動視窗按cmd+c或者直接關掉視窗結束程式
    • 執行redis-cli shutdown 輸出redis-cli ping檢驗 控制檯列印Could not connect to Redis at 127.0.0.1:6379: Connection refused 說明關閉成功

node端的簡單使用

  • node安裝redis npm install redis --save

  • 啟動redis客戶端

    const redis = require('redis');
    // 你啟動的redis埠和ip地址+options(可去官網自行查閱資料)
    const client = redis.createClient(6379, '127.0.0.1', {});
    // 監聽錯誤
    client.on('error', (err) => {
      console.log(err);
    })
    // 設定普通的string
    client.set("string key", "string val", redis.print);
    // 設定hash值
    client.hset("hash key", "hashtest 1", "some value", redis.print);
    client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
    // 設定map值
    client.mset('key1', 'val1', ... 'keyn', 'valn', '[callback]'); 
    
    //迴圈遍歷
    client.hkeys("hash key", function (err, replies) {
        console.log(replies.length + " replies:");
        replies.forEach(function (reply, i) {
            console.log("    " + i + ": " + reply);
        });
        // 退出
        client.quit();
    }); 
    複製程式碼

    更多命令使用請參考: github.com/NodeRedis/n…

  • 漂流瓶小功能

    • throw方法

        exports.throw = (bottle, callback) => {
              bottle.time = bottle.time || Date.now();
              const bottleId = Math.random().toString(16);
              const type = {
                male: 0,
                female: 1
              };
              console.log('at redis.js:', bottle);
              /*client.SELECT選擇資料庫編號*/
                client.SELECT(type[bottle.type], function (event) {
                  console.log(event);
                  /*client.HMSET 儲存雜湊鍵值*/
                    client.HMSET(bottleId, bottle, function (err, result) {
                      if (err) {
                        return callback({
                          code: 0,
                          msg: "過會兒再來試試吧!"
                        });
                      }
                      console.log('at redis.js:', result);
                      callback({
                        code: 1,
                        msg: result
                      });
                      /*設定過期時間為1天*/
                      client.EXPIRE(bottleId, 86400);
                    });
                });
            }
      複製程式碼
    • pick方法

          exports.pick = function (info, callback) {
                const type = {
                  all: Math.round(Math.random()),
                  male: 0,
                  female: 1
                };
                console.log('info is:', info);
                info.type = info.type || 'all';
                client.SELECT(type[info.type], function () {
                  /*隨機返回當前資料庫的一個鍵*/
                  client.RANDOMKEY(function (err, bottleId) {
                    if (!bottleId) {
                      return callback({
                        code: 0,
                        msg: "大海空空如也..."
                      });
                    }
                    /*根據key返回雜湊物件*/
                    client.HGETALL(bottleId, function (err, bottle) {
                      if (err) {
                        return callback({
                          code: 0,
                          msg: "漂流瓶破損了..."
                        });
                      }
                      callback({
                        code: 1,
                        msg: bottle
                      });
                      /*根據key刪除鍵值*/
                      client.DEL(bottleId);
                    });
                  });
                });
              }
      複製程式碼
      • app.js
        const redislib = require('./lib/redis');
                
                redislib.throw({
                  type: 'male',
                }, res => {
                  console.log(res);
                })
                redislib.pick({
                  type: 'male',
                }, res => {
                  console.log('at callback:', res);
                });
      複製程式碼

      到這裡已經跑通了程式,盡情享受redis吧~

      專案地址

相關文章