Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invalidate cache in Cloudfront using Java SDK

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?

like image 628
Ken John Avatar asked Jun 09 '26 05:06

Ken John


1 Answers

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).

like image 55
Arcones Avatar answered Jun 10 '26 19:06

Arcones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!