Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invalidate a file(to be refreshed) served from Cloudfront CDN via Java AWS SDK?

I am using Java SDK to uploaded images to S3, How do I invalidate a file in CloudFront so that it is refetched from s3 origin. How to do it via Java SDK ?

like image 830
Rajat Gupta Avatar asked Dec 05 '22 22:12

Rajat Gupta


2 Answers

import com.amazonaws.services.cloudfront;
import com.amazonaws.services.cloudfront.model.CreateInvalidationRequest;
import com.amazonaws.services.cloudfront.model.Paths;
import com.amazonaws.services.cloudfront.model.InvalidationBatch;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;

AWSCredentials awsCredentials = new DefaultAWSCredentialsProviderChain().getCredentials();
AmazonCloudFrontClient client = new AmazonCloudFrontClient(awsCredentials);

Paths invalidation_paths = new Paths().withItems("/path/to/invalidate/foo.jpg", "/path/file2.txt").withQuantity(2);
InvalidationBatch invalidation_batch = new InvalidationBatch(invalidation_paths, "unique_id_like_a_date");
CreateInvalidationRequest invalidation = new CreateInvalidationRequest("distributionID", invalidation_batch);
CreateInvalidationResult ret = client.createInvalidation(invalidation);

Note you can only have three concurrent invalidations; an invalidation seems to take 10-30 minutes.

like image 103
tedder42 Avatar answered Dec 28 '22 11:12

tedder42


From AWS Documentation:

You can have invalidation requests for up to 3,000 object URLs per distribution in progress at one time, and each invalidation request can include up to 3,000 object URLs. You can make as many invalidation requests as you want as long as you don't exceed this limit. For example, you can create 30 invalidations that invalidate 100 objects each, but as long as all 30 invalidations are still in progress, you can't create any more invalidations. If you exceed the limit, CloudFront returns an error message.

It usually takes 10 to 15 minutes for CloudFront to complete your invalidation request, depending on the number of object URLs that you included in the request.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html

like image 41
30thh Avatar answered Dec 28 '22 11:12

30thh