我有一个聊天应用程序,当我在输入消息后单击按钮时,该消息将发布到我的DynamoDB表中。该应用程序假定将消息发布一次,但是不知何故将其发布两次。
管道如下:
客户端单击send
按钮->击中我的Google Cloud Endpoint API->触发我的Google Cloud函数->调用我的AWS lambda函数->POSTS
消息DynamoDB。
在SO的帮助下,我已将问题隔离到异步调用Lambda的Google Cloud函数中,该函数对Lambda进行了两次排队。
使用异步,请求在实际执行之前排队。因此,如果您调用它一次,AWS将检查是否已经执行了一个,否则,它将添加另一个。
(AWS博客)
理想情况下,我想同步调用Lambda,但根据此Github帖子,我将被收取两次费用(?)。他提到增加我的功能的超时时间,但是已经设置为60秒-我的lambda有足够的时间将响应发送回去。还有其他机制可以让我的lambda两次排队吗?
供我参考,我的Google云功能如下:
let AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: ''
secretAccessKey: ''
region: ''
})
let lambda = new AWS.Lambda();
exports.helloWorld = async (req,res) =>{
let payload = {
pathParameters: req.query.p,
httpMethod: req.method,
body: req.method == "POST" ? req.body.message || req.body.user : null,
cognitoUsername: req.query.u
}
let params = {
FunctionName: '',
InvocationType: 'RequestResponse',
Payload: JSON.stringify(payload)
}
res.status(200).send( await lambda.invoke(params, function(err,data){
if (err){throw err}
else {return data.Payload}
}).promise())
}
解决方案:
基于@jarmod的解决方案,我的Cloud函数如下所示。相关部分在最后。
let AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: ''
secretAccessKey: ''
region: ''
})
let lambda = new AWS.Lambda();
exports.helloWorld = async (req,res) =>{
let payload = {
pathParameters: req.query.p,
httpMethod: req.method,
body: req.method == "POST" ? req.body.message || req.body.user : null,
cognitoUsername: req.query.u
}
let params = {
FunctionName: '',
InvocationType: 'RequestResponse',
Payload: JSON.stringify(payload)
}
// code changed only here
res.status(200).send( await lambda.invoke(params).promise())
}
编辑:
@Ngenator引起了我的注意,我的Google Cloud函数可能被触发了两次。供参考,这是我的API yaml配置:
swagger: '2.0'
info:
title: Cloud Endpoints + GCF
version: 1.0.0
host: service.run.app
x-google-endpoints:
- name: "service.run.app"
allowCors: "true"
schemes:
- https
produces:
- application/json
paths:
/function-2:
get:
operationId: get
parameters:
- name: p
in: query
required: true
type: string
- name: u
in: query
required: false
type: string
x-google-backend:
address: https://to.my/function-2
responses:
'200':
description: A successful response
schema:
type: string
post:
operationId: post
consumes:
- application/json
parameters:
- name: p
in: query
required: true
type: string
- name: u
in: query
required: false
type: string
- in: body
name: body
schema:
type: object
properties:
message:
type: string
user:
type: array
items:
type: string
x-google-backend:
address: https://to.my/function-2
responses:
'200':
description: A successful response
schema:
type: string
您的呼叫lambda.invoke
不正确。它包括两个回调并等待一个承诺。您应该使用其中一个,最好是后者:
const rc = await lambda.invoke(params).promise();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句