Home  >  Q&A  >  body text

tomcat - java data storage problem

As the title states, there is a login system, but the old project has no cache (I don’t have the right to add it), but different services have to use the data from previous http requests (distinguished by the user), and I want to save it to avoid duplication every time. Sending http requests wastes resources.

Background springmvc

Currently I think of 3 methods:

1. Throw it inside the session (HttpSessionListener), it should be the easiest, but I don’t know the potential problems
2. Throw it inside the threadlocal (controller makes a static threadlocal variable, or writes a contextholder)
3.controller Create a member of ConcurrentHashMap and put the data into it according to "user id, data obtained by http request". But this is definitely not feasible and may cause OOF in the heap area

Let’s talk about possible problems with the second option.
1. There is a possible memory leak problem mentioned on the Internet, causing OOF in PermGen. The original text is connected to ThreadLocal memory leak example analysis

I'm not sure if there will be a problem (the original text is a bit unclear), because ThreadLocalMap's set has a protection mechanism

2. Will the data string in the request thread appear? For example, a request thread serves the requests of two users (A and B) at the same time. B puts its own data in the request thread, covering A's, and When requesting thread service A, the data of B was obtained. .

迷茫迷茫2686 days ago658

reply all(1)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-06-12 09:23:38

    Method 1 is the simplest and most commonly used. If the number of users is too large, or load balancing is done, it is necessary to implement centralized storage of Session. There are many ready-made solutions that can support centralized storage of HttpSession, including Redis, MongoDB, and MySQL. There are all of them, search on GitHub.

    Method 2 does not solve the problem, mainly because after the user logs in, multiple requests may fall in multiple threads. The second point you mentioned is also a reason.

    Method 3 is also an implementation method. In fact, Tomcat's HttpSession is implemented using ConcurrentHashMap (only it uses sessionId instead of userId as the key), but one thing to note is that you must manage each Key-Value in the Map yourself. Life cycle, for example, if the Session times out, it must be removed in time.

    reply
    0
  • Cancelreply