vendredi 24 avril 2020

Injected resources into @Singleton EJB service

I'm using caffeine cache in my application to store some request results from external API. I decided it would be smart to use singleton so it would be just one cache in whole application. Second thing is that it injects stateless bean and its an API request service. This cache most likely will have high traffic

  1. Can this implementation be bottle neck somehow and maybe there is better way wire things up?

  2. Will singleton use just one instance of injected service (response takes about 3s, so i want to take advantage of caffeine multi-threading when refreshing values)? If its bad pattern how I should solve this?

  3. Should API call service be stateless local bean?
@Startup
@Singleton
class MyResultsCache {

    @EJB
    protected RestApiCallService service;

    protected Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
            .refreshAfterWrite(REFRESH_AFTER_MINUTES, TimeUnit.MINUTES)
            .expireAfterWrite(EXPIRE_AFTER_DAYS, TimeUnit.DAYS);
    protected LoadingCache<Object, Object> cache;

    @PostConstruct
    public void init() {
        loader = service::doRequestToApi;
        cache = cacheBuilder.build(loader);
    }
}

@Stateless
@LocalBean
class RestApiCallService  {
   private WebTarget target = ...; // web target creation here also

   public Object doRequestToApi(Object reqObj) {
      // amazing request impl...
      return target.request(..)post(..);
   }
}

Aucun commentaire:

Enregistrer un commentaire