本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
撰寫啟用回應串流的 Lambda 函數
撰寫回應串流函數的處理常式不同於典型的處理常式模式。撰寫串流函數時,請務必執行下列動作:
使用本機 Node.js 執行期提供的
awslambda.streamifyResponse()
裝飾項目包裝您的函數。從容地結束串流,以確保所有資料處理都完成。
設定處理常式函數以串流回應
為了向執行期指示 Lambda 應該串流函數的回應,您必須使用 streamifyResponse()
裝飾項目包裝函數。這會通知執行期使用適當的邏輯路徑來串流回應,並讓函數串流回應。
streamifyResponse()
裝飾項目接受的函數可接受以下參數:
event
– 提供函數 URL 調用事件的相關資訊,例如 HTTP 方法、查詢參數和請求內文。responseStream
– 提供可寫入的串流。context
– 提供方法和屬性,以及有關調用、函數以及執行環境的資訊。
responseStream
物件是 Node.js writableStream
pipeline()
方法。
範例 啟用回應串流的處理常式
const pipeline = require("util").promisify(require("stream").pipeline); const { Readable } = require('stream'); exports.echo = awslambda.streamifyResponse(async (event, responseStream, _context) => { // As an example, convert event to a readable stream. const requestStream = Readable.from(Buffer.from(JSON.stringify(event))); await pipeline(requestStream, responseStream); });
雖然 responseStream
提供寫入串流的 write()
方法,但仍建議您盡可能使用 pipeline()
pipeline()
可確保可寫入的串流不會被更快的可讀串流所淹沒。
結束串流
請確保在處理常式傳回之前正確結束串流。pipeline()
方法會自動處理這種情形。
對於其他使用案例,請呼叫 responseStream.end()
方法以正確結束串流。此方法發出訊號,表示不應向串流寫入更多資料。如果您使用 pipeline()
或 pipe()
寫入串流,則不需要此方法。
範例 使用 pipeline() 結束串流的範例
const pipeline = require("util").promisify(require("stream").pipeline); exports.handler = awslambda.streamifyResponse(async (event, responseStream, _context) => { await pipeline(requestStream, responseStream); });
範例 未使用 pipeline() 結束串流的範例
exports.handler = awslambda.streamifyResponse(async (event, responseStream, _context) => { responseStream.write("Hello "); responseStream.write("world "); responseStream.write("from "); responseStream.write("Lambda!"); responseStream.end(); });