iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
1
Microsoft Azure

白眼狼的30天Azure跳槽計畫系列 第 14

Day [14] Azure Cache for Redis-本機執行&測試

Use Azure Cache for Redis with Node.js

今天來練習在本機使用 Node.js 應用程式操作Azure Cache for Redis,以便後續可從前幾日建立的Azure Functuons 中來讓Webhook存取Cache。

首先在建立一個資料夾並在終端機輸入 npm init,並在資料夾下新增一個index.js檔案

$ npm init
$ touch index.js

完成後資料夾中會有package.json與index.js檔案
https://ithelp.ithome.com.tw/upload/images/20200929/201082817NaXRmtDLP.jpg
終端機輸入 npm install --save redis & npm install --save bluebird

$ npm install --save redis
$ npm install --save bluebird

https://ithelp.ithome.com.tw/upload/images/20200929/20108281DXFeJgfjxE.jpg
可以使用redis module撰寫程式了,修改index.js為下列code

const redis = require("redis");
const bluebird = require("bluebird");

const REDISCACHEHOSTNAME = '<YOUR_AZURE_REDIS_REDISCACHEHOSTNAME>'
const REDISCACHEKEY = '<YOUR_AZURE_REDIS_REDISCACHEKEY>'

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

async function testCache() {
    // Connect to the Azure Cache for Redis over the TLS port using the key.
    const cacheConnection = redis.createClient(6380, REDISCACHEHOSTNAME,
        { auth_pass: REDISCACHEKEY, tls: { servername: REDISCACHEHOSTNAME } });

    // Perform cache operations using the cache connection object...

    // Simple PING command
    console.log("\nCache command: PING");
    console.log("Cache response : " + await cacheConnection.pingAsync());

    // Simple get and put of integral data types into the cache
    console.log("\nCache command: GET Message");
    console.log("Cache response : " + await cacheConnection.getAsync("Message"));

    console.log("\nCache command: SET Message");
    console.log("Cache response : " + await cacheConnection.setAsync("Message",
        "Hello! The cache is working from Node.js!"));

    // Demonstrate "SET Message" executed as expected...
    console.log("\nCache command: GET Message");
    console.log("Cache response : " + await cacheConnection.getAsync("Message"));

    // Get the client list, useful to see if connection list is growing...
    console.log("\nCache command: CLIENT LIST");
    console.log("Cache response : " + await cacheConnection.clientAsync("LIST"));
}

這邊會用到REDISCACHEHOSTNAME(主機名稱)與REDISCACHEKEY(存取金鑰)
還記得我們昨天建立的Azure Redis嗎?這些資訊在Azure入口網站登入後選取建立的Redis Cache後點選
存取金鑰屬性複製取得如下圖:
https://ithelp.ithome.com.tw/upload/images/20200929/20108281LLGgyVD0cn.jpg
https://ithelp.ithome.com.tw/upload/images/20200929/201082814HQrjwm4C5.jpg
還沒建立Azure Redis的朋友可以參考-Day [13] Azure Cache for Redis-建置

在終端機輸入node index.js執行程式

$ node index.js

https://ithelp.ithome.com.tw/upload/images/20200929/20108281RfJKsqG6ME.jpg
測試成功明天,將在明天將Azure Functions上操作Azure Cache for Redis。


上一篇
Day [13] Azure Cache for Redis-建置
下一篇
Day [15] Azure Cache for Redis-Line Chatbot實作(ㄧ)
系列文
白眼狼的30天Azure跳槽計畫30

尚未有邦友留言

立即登入留言