在 SAP Kyma 上使用 Redis 服务
鏈接:https://developers.sap.com/tutorials/cp-kyma-redis-function.html
本地文件:C:\Code\referenceCode\SAP Kyma教程例子\redis-function
包含一個 deployment 和兩個 function:
函數(shù)1:cache-order
定義了三個依賴:
- axios
- redis
- handy-redis
環(huán)境變量
這些環(huán)境變量的用法,在代碼里使用 process.env 加上中括號引用。
cache-order 函數(shù)的三大主要邏輯:
(1)從 Kyma 傳入的 event 結(jié)構(gòu)里,獲得 Commerce 創(chuàng)建訂單的 ID.
(2) 根據(jù)訂單 ID,調(diào)用函數(shù) getOrderDetails,獲得訂單明細(xì)。
(3) 從訂單明細(xì)里獲得含稅的價格,調(diào)用函數(shù) cacheOrder,將價格存儲到 Redis 里:
getOrderDetails 的實現(xiàn):
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 環(huán)境變量,在 Kyma 控制臺里能夠找到:
cacheOrder 的實現(xiàn),調(diào)用 redis client hmset 方法:
resources
定義了 CPU 和內(nèi)存的 quota,以及源代碼:
這里的意思是,一旦應(yīng)用 mp-commerce-mock 的 order.created 事件觸發(fā),會調(diào)用 cache-order 這個 function:
函數(shù)2:get-order
該函數(shù)的實現(xiàn)文件里,還定義了一個 APIRule:
部署之后如圖:
定義了一個 gateway:
gateway: kyma-gateway.kyma-system.svc.cluster.local
從 Redis 里獲取數(shù)據(jù)的源代碼:
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!"} }關(guān)于如何測試這些 function,請參考 Jerry 這篇文章。
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的在 SAP Kyma 上使用 Redis 服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生活中哪些是有害垃圾 有害垃圾详细介绍
- 下一篇: 在 SAP Kyma 上部署一个 Go