A glanced around, ThreadLocal ThreadLocalMap added behind the internal implementation details

To understand:

Thread local variable. After assignment, values between threads are not visible. When used in conjunction with thread pools, local variables are cleared at the end of the thread.

Overall: . Within each thread maintains a ThreadLocal variables ThreadLocalMap threadLocals (key: ThreadLocal, value), ThreadLocal assignment values are operating in the variable, the variable is each thread private variables, Must not be visible between different threads.

ThreadLocal threadLocal = new ThreadLocal<>(); 1, threadLocal. The set ()

Set method, the first to get the current thread ThreadCurrent. CurrentThread (), then the getMap (Threadt) gain access to thread ThreadLocal. ThreadLocalMap variables, not empty, The set value is the key for the current TheadLocal instance, the value is the value of the incoming value, to create an empty empty ThreadCurrent. CurrentThread () and assignment.

2, threadLocal. The get ()

To get the current thread ThreadCurrent. CurrentThread (); For the current thread ThreadLocal ThreadLocalMap variable, if is empty, returns null, if not empty, according to the current TheadLocal instance value to obtain the corresponding value

Remove () removes the key of the current threadLocal instance from the current thread


Example: mysql dynamic data source switchover

Requirement: Distribute partial query requests to slave libraries based on the existing master slave database environment. Here only gives the general idea, does not post detailed

Thinking: custom annotations + + ThreadLocal + AbstractRoutingDataSource cut (dynamic data sources)

Add a custom annotation to the mybatis interface method to obtain the parameters of the slice (dynamic data source key) before execution. ThreadLocal writes the obtained key to the local thread variable. DynamicRoutingDataSource reads the data source specified by the current query from ThreadLocal when fetching the connection.

Custom annotations:

Section:

Remember to clear the thread’s local variables after cutting

Rewrite AbstractRoutingDataSource determineCurrentLookupKey method, obtain the specified data source from the ThreadLocal key

In addition, the configuration of dynamic data source: