2016-05-03 83 views
-1

我在Lambda中使用putItem JAVA函數的以下代碼。該功能正常工作,直到行client.putItem(itemRequest);。該功能正確讀取輸入。完成JUnit4測試(總計時間爲< 2秒)時,整個代碼可以正常工作,並且可以看到數據庫中的條目。但是,當在putItem行中使用Lambda控制檯進行測試時,這會失敗(5秒後超時)。putItem(itemRequest)在JUnit測試期間工作,但不在AWS Lambda控制檯上測試期間工作

public class HelloDB implements RequestHandler<UserClass, String> { 
AmazonDynamoDBClient client = null; 

public HelloDB() throws IOException { 
    AWSCredentials credentials = new PropertiesCredentials(HelloDB.class 
        .getResourceAsStream("AwsCredentials.properties")); 
    client = new AmazonDynamoDBClient(credentials); 
    System.out.println("Creds created"); 
} 

@Override 
public String handleRequest(UserClass input, Context context) { 
    System.out.println("U: " + input.getUserName() + " p: " + input.getPasswordHash()); 
    System.out.println("UI: " + input.userId + " O: " + input.getOpenIdToken()); 

    String tableName = "User"; 

    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); 

    item.put("userName", new AttributeValue().withS(input.getUserName())); 
    item.put("passwordHash", new AttributeValue().withS(input.getPasswordHash())); 
    item.put("userId", new AttributeValue().withN(input.getUserId().toString())); 
    item.put("openIdToken", new AttributeValue().withS(input.getOpenIdToken())); 

    PutItemRequest itemRequest = new PutItemRequest().withTableName(tableName).withItem(item); 
    System.out.println("item request"); 
    client.putItem(itemRequest); 
    System.out.println("client put item request"); 
    item.clear(); 
    return "Success"; 
} 

以下是錯誤消息:

"errorMessage": .... Task timed out after 5.00 seconds" 

當時間增加爲15秒,而不是5秒然後我得到這個錯誤:

"errorMessage": "Metaspace", 
"errorType": "java.lang.OutOfMemoryError" 
+1

「它失敗」並不是真正有用的描述;如果你真的希望我們幫助你,那麼「如何」是非常重要的。 – GhostCat

+0

它超時。所以基本上它不能把項目... – suku

+0

您是否啓用了Lambda函數的VPC訪問? –

回答

1

如果一個函數不獲取任何請求後,Amazon會自動將其從Lambda服務器中刪除,因此它不使用任何資源。如果發生這種情況,則在下一次請求進入時,必須將該功能重新部署到Lambda服務器,然後才能處理該請求。這被稱爲「冷啓動」

與使用python或nodejs編寫的代碼相比,我需要更長的時間和更多的資源來使用JAVA編寫的lambda函數從冷啓動運行。因此,最好分配至少10秒的時間限制和512MB內存來啓動。隨後的運行大約需要20-30毫秒。

下面是一個關於所有3種語言寫入的函數的冷啓動時間和隨後的運行時間的研究。

JUnit4測試運行速度比Lambda可能歸因於冷啓動。

相關問題