In this article, we will see how to enable a Java Lambda access to an AWS RDS MySQL instance.
Set up your AWS RDS MySQL instance (See Creating an AWS RDS MySQL Database with MySQL WorkBench)
This article will follow a similar approach for developing a Java CDK Approach as documented at Creating an AWS Serverless Java 11 Application with CDK (Lambda, S3, DynamoDb, API Gateway)
Create a Java Lambda to query and update data in this database.
Assumption: You have already setup your AWS Console and Eclipse environment as documented at Getting started with AWS, Java 11 (Amazon Corretto), Eclipse and AWS Toolkit
- Create a Java MySQL Lambda project using CDK
cdk init app --language java
2. Open the project up in Eclipse
File -> Open Projects from File System
Your Eclipse should now look like the following:
Ensure your Java Build Path is set up correctly with JavaSE-11 and Maven Dependencies selected (Right click the Project Explorer in Eclipse to open the build path):
We will now work to create a Java Lambda to access the Postgres Database we created above.
Create AWS Lambda Handler GetRDSDataLambdaHandler class by right clicking in the Project Explorer New->Class
Refer to the code located at https://github.com/collin-smith/mysqljlambda for the following 3 classes or files:
//MySQL RDS Configuration
(** Within the MysqljlambdaStack.java class, ensure that the RDS information is configured properly to your instance in the class above to connect to the RDS MySQL instance. Then endpoint can be retrieved from the AWS console for the RDS instance)
Once the files have been updated you should be able to compile the project by right clicking on your project in the Project Explorer -> Run As -> Maven Build
Type in “clean install” and press run
Once built, you should be able to go to the cmd console and complete the following steps to deploy it to your aws environment:
The Lamdba endpoint should now be deployed into your AWS environment and you should have an endpoint you can test with PostMan
That is what it looks like for a successful run of the Lambda. This Lambda reads the records from the table and it also inserts a record into the table.
This can be seen when you run the following SQL command in the MySQL WorkBench client to see that the Lambda has inserted a new record into the MySQL database.
SELECT * FROM LETTERHISTORY
Verify in CloudWatch Log Groups if you have any unexpected errors for troubleshooting. I would look at the Log Groups for this Lambda to understand the errors a bit more.
This concludes how to set up a Java Lambda query and make updates to a MySQL RDS instance.
If you have finished with the MySQL instance, go to the RDS section in the AWS console and delete the data base instance.
Also, to remove the Lambda code, you should run cdk destroy to remove the code deployed by the cdk project.