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의 라이센스가 부여되었습니다.  Twitter™ 및 Facebook 게시물은 Creative Commons 약관을 적용받지 않습니다.

법적 고지 사항   |   온라인 개인 정보 보호 정책