May 10, 2020
Estimated Post Reading Time ~

Programmatic Cache Invalidation in AEM 6

There are three ways of doing it.

1. By sending post request to the dispatcher cache invalidation URL as follows.
HttpClient client = new HttpClient();
  HostConfiguration configuration = new HostConfiguration();
                // This uri is http://dispatcherhost:dispatcherport/dispatcher/invalidate.cache
                // Without this host configuration there will be and exception with the message "Host is null"
  configuration.setHost(uri);
  client.setHostConfiguration(configuration);
  PostMethod post = new PostMethod(uri);
                // CQ-Action:Delete will delete the cache from dispatcher.
                // For cache invalidation Activate action should be used.
  post.setRequestHeader("CQ-Action", "Activate");
                // pagePath specifies the page that needs to be invalidated
  post.setRequestHeader("CQ-Handle", pagePath);
  StringRequestEntity body = new StringRequestEntity(pagePath, null, null);
  post.setRequestEntity(body);
  post.setRequestHeader("Content-length",String.valueOf(body.getContentLength()));
  client.executeMethod(post);
  post.releaseConnection();

2. Using DispatcherFlusher provided by ACS commons.
First make reference to DispatcherFlusher

       @Reference
       private DispatcherFlusher dispatcherFlusher;

Next make use of it to flush the cache

             dispatcherFlusher.flush(getResourceResolver(repo.loginAdministrative(null)), pagePath);

3. FlushService (Available in AEM 6.2+ versions)
FlushService flushService = sling.getService(Replicator.class);
             flushService.sendFlushUrl("admin",FlushService.FlushType.IMMEDIATE_FLUSH, pagePath,FlushService.RefetchType.IMMEDIATE_REFETCH,new String[] {pagePath});


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.