I have an interface called processor:
public interface Processor {
MyResponse process(Request request, String id);
}
I have two implementations of this processor, one synchronous, the other asynchronous (both Spring Service classes):
This is Sync Version, completes the job and give a fully populated response:
@Service
public class SynchrnousProcess implements Processor {
@Override
public MyResponse process(Request request, String id) {
Job job = getJob(request);
JobParameters parameter = buildParams(request, id);
JobExecution jobExecution = kickOfJob(job, request, parameter);
return buildResponse(request, trackingId, jobExecution);
}
}
This is Async version, which adds requests to blocking queue:
@Service
public class AsyncProcess implements Processor {
private BlockingQueue<Pair> requestQueue = new ArrayBlockingQueue<>(100);
@Override
public MyResponse process(Request request, String id) {
//add request to requestQueue
}
public void completeProcess() {
//take data from queue and process
log.info("start process !!!!!!!!!!!!!!!");
if (!CollectionUtils.isEmpty(requestQueue)) {
requestQueue.stream().forEach(pair -> {
String trackingId = String.valueOf(pair.getFirst());
FeedDto feedDto = (FeedDto) pair.getSecond();
Request request = feedDto.getRequest();
Job job = getJob(request);
JobParameters parameter = getJobParameters(request, trackingId);
JobExecution jobExecution = runJob(job, request, parameter);
}
}
As you can see, completeProcess()
takes data out of the queue and processes the job. Common code to do with getting job, building param is duplicated between synchronous run and async.
Another thread runs completeProcess()
in background.
I want to achieve a clean design and move common code that are shared by the two interface implementations in one place. How can I achieve this for what I am trying to achieve? It will be really helpful to see an example of the design pattern to use in this case?
In Addition, any suggestion as to where the ExecutorService to process the queued requests should be initiated and how the threads to process these should be started will help a lot.
Aucun commentaire:
Enregistrer un commentaire