Issue

How to detect if the code is running on the master node in a cluster (if clustering is enabled).

Solution

Use the repository descriptor "crx.cluster.master. But note that the value could be null if clustering is disabled on some versions of CRX. Use the following code (it works in any CRX-based app using CRX2.1.0.10+.)

package sample.demo;
public interface ClusterService {
public boolean isMaster();
}
package sample.demo;

import sample.demo.ClusterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.Reference;
import javax.jcr.Repository;

@Component(metatype = false)
@Service(value = ClusterService.class)

public class MyClusterAwareService implements ClusterService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyClusterAwareService.class);

    @Reference
    private Repository repository;
    
    public boolean isMaster() {
       String v = repository.getDescriptor("crx.cluster.master");
        boolean isOnMaster = v == null || Boolean.parseBoolean(v);
        LOGGER.info("MyClusterAwareService isMaster" + isOnMaster );
        return isOnMaster;
    }
    
    @Activate
    protected void activate() {
        LOGGER.info("service activated" );
    }
    @Deactivate
    protected void deactivate() {
        LOGGER.info ("service deactivated");
    }
}
<%
sample.demo.ClusterService clusterService =  sling.getService(sample.demo.ClusterService.class);
%>
Am I master <%= clusterService.isMaster() %>

註解:

Note: In CQ5 there are some libraries to help implement cluster aware OSGi services.See here.

** CRX 2.1 must have hot fix 2.1.0.10 applied

註解:

AEM 5.6.1 (CRX 2.4.30) onward use new topology API. Details at http://helpx.adobe.com/cq/kb/create-cluster-aware-osgi-service.html

此産品由 Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License 授權  Creative Commons 條款未涵蓋 Twitter™ 與 Facebook 文章。

法律說明   |   線上隱私權政策