mardi 27 juillet 2021

Spring - alternative way to have request context in child thread

In java application using spring I'm facing situation when I need to create asynchronous REST endpoint for some small data processing.

I.e. current idea is:

  • we got request for processing
  • as soon as we verify it could be processed we return 200 OK
  • at the same time we create child thread in which processing will run

Child process is used because we need to have Request / Session in that processing thread (because current user should be checked and recorded during processing - due to legacy code it's hard to do before).

I use solution found on StackOverflow and it works like a charm.

However some of colleagues on review regard it "insecure" to enable inherited request context on all thread. Thus I'm looking for other possible approach.

What I tried is to share request attributes to child thread manually:

    var attrs = RequestContextHolder.getRequestAttributes();
    new Thread(() -> {
        RequestContextHolder.setRequestAttributes(attrs);
        // ...
    });

This partly works, but only till response is sent in parent thread. After this I get exception with explanation Cannot ask for request attribute - request is not active anymore!

I tried to specify that parent's attributes are inheritable - but this doesn't help:

    var attrs = RequestContextHolder.getRequestAttributes();
    RequestContextHolder.setRequestAttributes(attrs, true);  // inheritable
    new Thread(() -> {
        RequestContextHolder.setRequestAttributes(attrs);
        // ...
    });

(I got error saying that I have no active request, If I'm not wrong - tried few more similar variations)

So any further hints are welcome (or explanations of my mistakes). Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire