April 10, 2020
Estimated Post Reading Time ~

Robust Sling Eventing using Sling Jobs

So far we have used OSGi Event Admin for event publishing that uses the publisher-subscriber model. Though it works really well, there is a downside in using this:

– No guarantee of delivery

As soon as an event is published, the job of the publisher is done. No matter whether any subscriber has worked on it or not, the event just dies down.

– No distributed delivery

OSGi Event Admin doesn’t fare well with the clustered environment.

Sling Job mechanism takes care of these shortcomings and is persistent(persisted under /var/eventing/jobs). It guarantees delivery and comes with lots of configurable options like a number of retries and retry intervals. In AEM 6.1 release notes, Adobe recommends using this new Eventing mechanism as old eventing has deprecated.

To implement it, you need a publisher and a consumer:
The publisher makes use of JobManager to add a job:

@Reference
private JobManager jobManager;

@Override
public void publishJob() {
final Map<String, Object> jobProperties = new HashMap<String, Object>();
jobProperties.put("jobName", "some dummy job");
jobProperties.put("count", 3);
jobProperties.put("job location", "yet another city");
jobManager.addJob("my/sling/job", jobProperties);
}

Here addJob method takes 2 parameters(same as event service) – job topic and properties.

Consumer subscribes to that job topic and processes it. In case of successful execution, JobResult.OK should be returned. In case there is some issue in execution but you need to keep a job for retry, use JobResult.FAILED, else use JobResult.CANCEL that cancels the job right away.

@Component
@Service(value={JobConsumer.class})
@Property(name=JobConsumer.PROPERTY_TOPICS, value="my/sling/job")
public class MyJobConsumer implements JobConsumer {
public JobResult process(final Job job) {
System.out.println("=========================");
System.out.println(job.getProperty("count"));
System.out.println("=========================");

// process the job and return the result
int count = (Integer)job.getProperty("count");
if(count > 3){
return JobResult.FAILED;
}

return JobResult.OK;

}
}

“Apache Sling Default Job Queue” maintains a default configuration of the queue. We can also maintain a separate queue for a pool of job topics that we create. “Apache Sling Job Queue Configuration” is a factory configuration that takes care of this.



By aem4beginner

No comments:

Post a Comment

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