问题
I am trying to build a microservice API using AWS (lambda + s3 + apiGateway) and I have noticed that all my lambdas have the same weight, so it seems like I am uploading the full project to every lambda instead of the needed resources.
Is there any way to upload just the resources I need for each function? Will this minimize the execution time? Is it worth to do it?
回答1:
Going to answer this in 2 parts:
(1) The obligatory "Why do you care?"
I ask this because I was really concerned too. But after testing, it doesn't seem like the size of the bundle uploaded (the jars in the lib folder of the lambda distribution bundle) seemed to really affect anything expect maybe initial upload time (or maybe S3 usage if you are going that route).
For the sake of sanity, rather than having a bunch of nano projects and bundles, I have a single Java Lambda API module and then I upload the same artifact for every Lambda.
At some point, if it makes sense to separate for whatever reason (micro service architecture, separation of code, etc), then I plan on splitting.
Now having said that, the one things that REALLY seems to affect Java based lambdas is class loading time. You mentioned you use Spring. I would recommend you not use Spring configuration loading as you will probably end up executing a bunch of code you never really need.
Remember, ideally your lambdas should be in the 100ms range. I had a case where I was using the AWS SDK and initializing the AWSClient was taking 13 seconds! (13000 ms). When I switched to using Python of Node, it went to 56ms...
Remember that you get charged by time, and a 1000x factor is no laughing matter :)
(2) If you've decided on splitting, I'd recommend using the gradle distribution plugin with child projects to make each child project and child project zip distribution "light". I went down this road but realized I would really be splitting my components really fine... and I'd either be duplicating configurations across projects. Or if I made a project dependency, I would simply end up bundling up the entire dependency tree again.
If you already know what you need to cherry pick without relying on gradle / maven to handle the dependencies for you, you can create gradle zip tasks to create different Lambda distribution packages.
AWS documentation: http://docs.aws.amazon.com/lambda/latest/dg/create-deployment-pkg-zip-java.html
回答2:
You will need to create and build 3 different jars for each of your lambda functions and in each of the jar simply package the classes and their required resources rather than creating a super-set jar that has classes and resources for each of the lambda functions.
This way your jars will get lighter.
For more details about building lambda jars see Building AWS Lambda jar
来源:https://stackoverflow.com/questions/44782208/how-can-i-minimize-the-weight-of-my-lambda-functions