Use of thread variable threadlocal

Source: Internet
Author: User

We sometimes make multiple inquiries via token (pig: token is a key in Redis), such as:

Once in the login interceptor, once in the controller's business query, so there is a waste of performance and resources problems!!!

So how do you pass the data in the interceptor to the controller?

There are two types of scenarios:

1. Place the user object in the Request object

2, implemented with threadlocal thread variables (objects are in the same thread before entering Tomcat and generating a response)

Realize:

1, define a threadlocal related class


public class Userthreadlocal {
private static threadlocal<user> user_local = new threadlocal<> ();

Provide set and get methods externally
public static void SetUser (user user) {
User_local.set (user);
}
public static User GetUser () {
return User_local.get ();
}
}

2. Place the user object in the threadlocal in the login interceptor

Query to the user, put the user into threadlocal
Userthreadlocal.setuser (user);

3, the user can be obtained via threadlocal in the service

Get the user object from the threadlocal thread variable
User user = Userthreadlocal.getuser ();

Use of thread variable threadlocal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.