I am trying to invalidate cache in AWS cloudfront using the JAVA SDK but I am finding it a nightmare to find the relevant information. I already created the project and I am trying to figure out how to use com.amazonaws.services.cloudfront.AmazonCloudFrontClient to connect to cloudfront and call the invalidate api.
com.amazonaws.services.cloudfront.AmazonCloudFrontClient
I found an answer to a question similar to mine back in 2016 that recommended the following approach:
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);
However some of these classes are now deprecated and/or non-existent anymore.
Can someone please help with the correct way to invoke invalidation API in Cloudfront via JAVA?
I successfully invalidated the cache of certain paths with AWS Java SDK 2.x with this:
Paths invalidationPaths = Paths.builder()
.items("/thing.txt", "/foo/bar/*")
.quantity(2)
.build();
InvalidationBatch invalidationBatch = InvalidationBatch.builder()
.paths(invalidationPaths)
.callerReference("arcones")
.build();
CreateInvalidationRequest createInvalidationRequest = CreateInvalidationRequest.builder()
.distributionId(distributionID)
.invalidationBatch(invalidationBatch)
.build();
cloudFront.createInvalidation(createInvalidationRequest);
Take in mind that the invalidation is asynchronous, so it will be issued to your CloudFront distribution when you run this and will take a while to be processed (you can notice that the invalidation has finished when the status becomes Completed).
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