Issue
I'm writing small Data downloading service function using Spring Boot 2.7. I deployed it in the AWS lambda function. At the cold starting each time it initializes twice as shown in the image below.
src="https://i.stack.imgur.com/qZK0M.png" alt="enter image description here" />
Here is the lambderHandler.java
public class LambdaHandler implements RequestHandler<SQSEvent, String> {
private static final ApplicationContext applicationContext = SpringApplication.run(DataDownloaderService.class);
@Override
public String handleRequest(SQSEvent event, Context context) {
context.getLogger().log("Input: " + event);
if (!event.getRecords().isEmpty()) {
SQSEvent.SQSMessage firstRecord = event.getRecords().get(0);
String eventBody = firstRecord.getBody();
if (eventBody != null) {
ProductDownloadService productDownloadService = applicationContext.getBean(ProductDownloadServiceImpl.class);
try {
productDownloadService.downloadProductData(JsonUtil.getUserInfo(eventBody));
return "Successfully processed";
} catch (IOException e) {
return "Error in data downloading: " + e.getMessage();
}
}
}
return "Data download not success";
}
}
Here is the DataDownloaderService.java
@SpringBootApplication
@ComponentScan(basePackages = {"com.test.*"})
@EntityScan(basePackages = {"com.test.*"})
public class DataDownloaderService {
}
Why spring boot lambda function initialize multiple times at the cold start? Did I have some misconfiguration here or is it a bug?
Solution
I found a workaround to fix this issue from here.
Here is the workaround for the above code.
public class LambdaHandler implements RequestHandler<SQSEvent, String> {
private ApplicationContext applicationContext;
/**
* Entry point in the lambda function
* @param event
* @param context
* @return
*/
@Override
public String handleRequest(SQSEvent event, Context context) {
return initDataDownloaderService(event, context);
}
/**
* initialize application context and Data downloader service
*
* @param event
* @param context
* @return
*/
private String initDataDownloaderService(SQSEvent event, Context context) {
if (applicationContext == null) {
applicationContext = SpringApplication.run(DataDownloaderService.class);
}
context.getLogger().log("Input: " + event);
if (!event.getRecords().isEmpty()) {
SQSEvent.SQSMessage firstRecord = event.getRecords().get(0);
String eventBody = firstRecord.getBody();
if (eventBody != null) {
ProductDownloadService productDownloadService = applicationContext.getBean(ProductDownloadServiceImpl.class);
try {
productDownloadService.downloadProductData(JsonUtil.getUserInfo(eventBody));
return "Successfully processed";
} catch (IOException e) {
return "Error in data downloading: " + e.getMessage();
}
}
}
return "Data download not success";
}
}
Answered By - Maneesha Randeniya
Answer Checked By - Marilyn (JavaFixing Volunteer)