I need to develop an AWS Lambda Java function to retrieve some records from RDS MySQL database.
Should I use JDBC? Should I use the standard JDBC example:
try {
String url = "jdbc:msql://200.210.220.1:1114/Demo";
Connection conn = DriverManager.getConnection(url,"","");
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
while ( rs.next() ) {
String lastName = rs.getString("Lname");
System.out.println(lastName);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
Lambda can work seamlessly with RDS instances, as long as you remember the specific requirements for this particular setup. Since RDS instances are running in your VPC and Lambda by default does not have access to those resources, you'll need to configure the VPC connection when creating a Lambda function.
Create a Lambda function to access the ExampleDB database, create a table (Employee), add a few records, and retrieve the records from the table. Invoke the Lambda function and verify the query results. This is how you verify that your Lambda function was able to access the RDS MySQL instance in the VPC.
Sign in to the AWS Management Console and open the Amazon RDS console at https://console.aws.amazon.com/rds/ . In the navigation pane, choose Databases to display a list of your DB instances. Choose the name of the MySQL DB instance to display its details. On the Connectivity & security tab, copy the endpoint.
First, open the security group to your RDS DB instance to allow traffic from your computer. Open the Elastic Beanstalk console , and in the Regions list, select your AWS Region. In the navigation pane, choose Environments, and then choose the name of your environment from the list.
Step 1:
AWS service roles ->
a) Select aws lambda
b) Attach policy "AWSLambdaFullAccess"
Step 2:
Right click on project select Run as --->5.maven build...
for goal provide name package shade:shade
Go to project folder and target/lamda-0.0.1-SNAPSHOT-shaded.jar
Step 3:
name: time-test
a) runtime-java
b) upload .zip(.jar) file (target/lamda-0.0.1-SNAPSHOT-shaded.jar)
Provide package.class-name::myhandler
-> Handler
Role -> lambda-vpc-exceution-role
vpc provide rds-vpc details (this should work in same vpc group)
Create function
In the Action drop down list select configure test event result will shown down like this "Execution result: succeeded (logs)"
Yes, you need to use standard JDBC code in your lambda function class. The code you provided looks okay. There are a few more things you need to do when accessing RDS or any other RDBMS through a Lamda function -
You can test the Lambda function through the console, and see the actual output in the CloudWatch logs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With