Silent User
Silent User

Reputation: 2767

Where should I store a variable that I want to access throughout my Tomcat REST ws?

I have a REST web service running in Tomcat version 7 using Jersey 1.18. Each request that comes in has a custom header called 'request-id'. I would like to store this request id in some place so that all classes have access to this request id and can use it for logging.

The main thing is, this has to be on a per request basis. The request-id for request A is different than that of request B.

Where can I store such a variable? Some sort of a Context which is valid on a per request basis.

Upvotes: 0

Views: 393

Answers (1)

jny
jny

Reputation: 8067

You can store it in ThreadLocal. But you have to be careful with it. You would need to store it on receiving the request and clear it up when returning the response. You would probably want to write static utility methods to store and retrieve request id something like that:

public class RequestIdUtil {

    private static final ThreadLocal<String> requestIdHolder = new ThreadLocal<String>();

    private RequestIdUtil() {
        // to prevent initialization
    }

    public static void setRequestId(String requestId) {
        requestIdHolder.set(requestId);
    }

    /**
     * 
     * @return requestId
     *         
     */
    public static String getRequestId() {
        return requestIdHolder.get();
    }

    public static void remove() {
        requestIdHolder.remove();
    }



}

In this example remove needs to be called in the end of processing of every request even if Exception is thrown.

Upvotes: 1

Related Questions