Understanding Decorators in Armeria

375 Views Asked by At

I am just starting out with Armeria and struggling to fully understand some things.

I implemented DecoratingHttpServiceFunction in order to supply requests to a service with a Hibernate session.

@Override
public HttpResponse serve(HttpService delegate, ServiceRequestContext ctx, HttpRequest req) {
  ... // setup session for the request context
  HttpResponse response = delegate.serve(ctx, req);
  ... // close session
  return response;
}

But apparently the session gets closed before the service actually gets called and the request returned from delegate.serve is an instance of DeferredHttpResponse. Is my approach just completely wrong or is there a better way to do what I want to do?

1

There are 1 best solutions below

0
On BEST ANSWER

In Armeria, all requests and responses are handled asynchronously. Therefore, returning from delegate.serve(ctx, req) in your code does not guarantee that the request has been fully processed.

To perform a certain action after a request is fully handled, you need to add a callback to the HttpResponse returned by the delegate.serve(ctx, req):

@Override
public HttpResponse serve(HttpService delegate, ServiceRequestContext ctx, HttpRequest req) {
  ... // setup session for the request context
  HttpResponse response = delegate.serve(ctx, req);
  response.whenComplete().handle((unused1, unused2) -> {
      ... // close session
  });
  return response;
}