1. 程式人生 > 其它 >在 SAP Kyma 上使用 Redis 服務

在 SAP Kyma 上使用 Redis 服務

連結:https://developers.sap.com/tutorials/cp-kyma-redis-function.html

本地檔案:C:\Code\referenceCode\SAP Kyma教程例子\redis-function

包含一個 deployment 和兩個 function:

函式1:cache-order

定義了三個依賴:

  • axios
  • redis
  • handy-redis

環境變數

這些環境變數的用法,在程式碼裡使用 process.env 加上中括號引用。

cache-order 函式的三大主要邏輯:

(1)從 Kyma 傳入的 event 結構裡,獲得 Commerce 建立訂單的 ID.

(2) 根據訂單 ID,呼叫函式 getOrderDetails,獲得訂單明細。

(3) 從訂單明細裡獲得含稅的價格,呼叫函式 cacheOrder,將價格儲存到 Redis 裡:

getOrderDetails 的實現:

async function getOrderDetails(orderCode) {
  const ordersUrl = `${COMM_GATEWAY_URL}/${process.env.SITE}/orders/${orderCode}`;
  console.log("Getting ordering details via: %s", ordersUrl, " for orderCode: ", orderCode);
  const response = await axios.get(ordersUrl);
  console.log(JSON.stringify(response.data, null, 2));
  return response.data;
}

程式碼裡的 COMM_GATEWAY_URL 環境變數,在 Kyma 控制檯裡能夠找到:

cacheOrder 的實現,呼叫 redis client hmset 方法:

resources

定義了 CPU 和記憶體的 quota,以及原始碼:

這裡的意思是,一旦應用 mp-commerce-mock 的 order.created 事件觸發,會呼叫 cache-order 這個 function:

函式2:get-order

該函式的實現檔案裡,還定義了一個 APIRule:

部署之後如圖:

定義了一個 gateway:
gateway: kyma-gateway.kyma-system.svc.cluster.local

從 Redis 裡獲取資料的原始碼:

const hredis = require("handy-redis");

const client = hredis.createNodeRedisClient({
  port:  process.env["REDIS_PORT"],
  host: process.env["REDIS_HOST"],
  password: process.env["REDIS_PASSWORD"]
});

module.exports = { 
  main: async function (event, context) {
    try {   
      const orderCode = event.extensions.request.query.orderCode;
      let result = await processGetRequest(orderCode);
      return result ? result : {"error": "orderCode was not found"};
    }
    catch(err) {
      console.log("an error occurred...", err);
      event.extensions.response.status(500).json({"error": err});
    }
  }
}

async function processGetRequest(orderCode){    
  if(orderCode !== undefined){
    console.log("getting order from cache: ", orderCode);
    return client.hgetall(orderCode);
  }else{
    throw "No orderCode received!"
  }
}

關於如何測試這些 function,請參考 Jerry 這篇文章

更多Jerry的原創文章,盡在:"汪子熙":