dimanche 7 mars 2021

How to write Java rest client calling multiple microservices in modular manner?

I am writing a Java library that will call multiple services / REST endpoints to perform GET/PUT/POST etc. Planning to use OkHttpClient library call these services in sync and/or async.

Does it make sense to write a base class for establishing connection to each service?

public class ConnectionKlass {

  private OkHttpClient client;
  int timeout;
  int wTimeout;

  public ConnectionKlass(int timeout, boolean wTimeout){
    this.client=new OkHttpClient.Builder()
        .connectTimeout(timeout, TimeUnit.SECONDS)
        .writeTimeout(wTimeout, TimeUnit.SECONDS)
        .build();
  }
}

And then write each service client class like following?

public class ValidationServiceClient {
  
   private connection;

   public ServiceAClient(reqId, timeout, wTimeout) { this.connection = ConnectionKlass(..); }
   public validate(headers, body..) {...}
   public asyncValidate(headers, body..) {...}
   ...
}

public class MessageServiceClient {
  
   private connection;

   public ServiceBClient(reqId, timeout, wTimeout) { this.connection = ConnectionKlass(..); }
   public notify(eventType, message) {...}
   public asyncNotify(eventType, message) {...}
   ...
}

I am not new to Java but trying to gauge what a good design / implementation would look like? Is there a specific design pattern that I should use to maximize modularity and ease maintainability?

Aucun commentaire:

Enregistrer un commentaire