2017-06-23 115 views
3

有誰知道我如何通過AWS Lambda函數連接到PostgreSQL數據庫。我在網上搜索它,但我找不到任何關於它的信息。如果你能告訴我如何去做,那會很棒。AWS Lambda函數連接到Postgresql數據庫

如果你能發現我的代碼有問題(node.js),那會很好,否則你能告訴我如何去做?

exports.handler = (event, context, callback) => { 
    "use strict" 
    const pg = require('pg'); 
    const connectionStr = 
     "postgres://username:[email protected]:port/db_name"; 
var client = new pg.Client(connectionStr); 
client.connect(function(err){ 
    if(err) { 
     callback(err) 
    } 
    callback(null, 'Connection established'); 
}); 
context.callbackWaitsForEmptyEventLoop = false; 
}; 

的代碼拋出一個錯誤: 找不到模塊「PG」

我寫它直接在AWS上的Lambda和是否是有區別什麼都沒有上傳。

+0

plz分享你採用的最終解決方案。是不是必須要求'pg'並連接每個lambda函數?這是做到這一點的最佳方式嗎? – mythicalcoder

回答

1

I wrote it directly on AWS Lambda and didn't upload anything if that makes a difference.

是的,這使差異! Lambda不提供第三方庫。只要您對第三方庫有依賴關係,您就需要手動壓縮並上傳Lambda代碼或使用API​​。

富勒更多的信息:Lambda Execution Environment and Available Libraries

1

您需要參考Creating a Deployment Package (Node.js)

Simple scenario – If your custom code requires only the AWS SDK library, then you can use the inline editor in the AWS Lambda console. Using the console, you can edit and upload your code to AWS Lambda. The console will zip up your code with the relevant configuration information into a deployment package that the Lambda service can run.

Advanced scenario – If you are writing code that uses other resources, such as a graphics library for image processing, or you want to use the AWS CLI instead of the console, you need to first create the Lambda function deployment package, and then use the console or the CLI to upload the package.

你的情況下,像我這樣的落下的高級場景。所以我們需要創建一個部署包然後上傳它。在這裏我做了什麼 -

  1. 的mkdir部署
  2. CD部署
  3. 六index.js
  4. 寫你的拉姆達代碼文件。確保您的處理程序名稱在創建時爲index.handler。
  5. NPM安裝PG
  6. 您應該看到其中有多個模塊,它
  7. 包部署目錄爲zip文件部署目錄中創建node_modules目錄並上傳到LAMBDA。
  8. 你要善於然後

注:NPM安裝將安裝node_modules目錄下相同的目錄節點模塊,除非它認爲,在父目錄node_module目錄。首先執行npm init,然後按npm install確保模塊安裝在同一目錄中進行部署。

+0

所以在每個exports.handler函數中我們需要導入pg然後連接到數據庫?這是做到這一點的正確方法嗎? – mythicalcoder

+0

@mythicalcoder查看http://opensourceforgeeks.blogspot.in/2017/11/how-to-connect-to-postgres-rds-from.html –