iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 15
1
Microsoft Azure

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

Day [15] Azure Cache for Redis-Line Chatbot實作(ㄧ)

Azure Functions上操作Azure Cache for Redis

回顧一下-Day [11] Azure Cache for Redis-Chatbot 搜尋資料時間優化
我們想要利用Azure Cache for Redis緩存口罩公開資料,避免多餘的查詢動作,因此必須在我們部署Line Webhook的Azure Functions上操作Azure Cache for Redis。

由於Redis Cache與Line官方帳號都有一些重要參數會在程式中使用到,為了方便管理我們在Azure Functions專案中新增config.ts檔案,將Line官方帳號的cannelSecret, channelAccessToken與Redis Cache的REDISCACHEHOSTNAME,REDISCACHEKEY 寫入。忘記在哪裡取得的朋友可參考-Day [8] Azure Functions-使用 LINE Messaging APIDay [14] Azure Cache for Redis-本機執行&測試

config.ts:

export const LINE = {
    channelSecret: "<YOUR_CHANNEL_SECRET>",
    channelAccessToken: "<YOUR_CHANNEL_ACCESS_TOKEN>"
};

export const REDIS = {
    REDISCACHEHOSTNAME: '<YOUR_AZURE_REDIS_REDISCACHEHOSTNAME>',
    REDISCACHEKEY: '<YOUR_AZURE_REDIS_REDISCACHEKEY>'
}

接下來為了能使用Azure Cache for Redis來儲存,搜尋口罩公開資料的快取資料,我們在專案中新增一支RedisCache.ts程式,其中redis.createClient所需的參數可由上述的config.ts取得。

昨天我們已經練習過如何在local透過簡單的Node.js操作Azure Cache for Redis,現在我們要在Azure Functions的環境中操作可如法炮製,新增2支function以滿足緩存資料與取得資料的需求:setMask(),getMask()
這邊要注意的是原本透過公開資料端點取得的資料為JSON物件格式(可參考-Day [10] Azure Functions-Line Chatbot實作(二)),但Redis Cache存入的資料需為字串,因此需要透過JSON.stringify(), JSON.parse() 語法來處以轉換格式的問題。

RedisCache.ts:

const redis = require("redis");
const bluebird = require("bluebird");
import { REDIS } from '../config'

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

const cacheConnection = redis.createClient(6380, REDIS.REDISCACHEHOSTNAME,
    { auth_pass: REDIS.REDISCACHEKEY, tls: { servername: REDIS.REDISCACHEHOSTNAME } });

export const setMask = async (key: string ,maskSnapshot: any) => {
    console.log("\nCache command: SET Message");
    await cacheConnection.setAsync(key, JSON.stringify(maskSnapshot));
}

export const getMask = async (key: string) => {
    console.log("\nCache command: GET Message");
    const masCache = await cacheConnection.getAsync(key)
    return JSON.parse(masCache)
}

準備好上面的程式後,明天我們將繼續完成Line Cahtbot的資料緩存服務!


上一篇
Day [14] Azure Cache for Redis-本機執行&測試
下一篇
Day [16] Azure Cache for Redis-Line Chatbot實作(二)
系列文
白眼狼的30天Azure跳槽計畫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言