当前位置:网站首页>Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
2022-07-06 21:25:00 【Huawei cloud developer Alliance】
Abstract : We can process every request , No need to Controller as well as Service The method in passes values layer by layer , You only need to take the value directly through the local variable .
This article is shared from Huawei cloud community 《 Skillfully used in interceptors ThreadLocal Avoid passing values layer by layer 》, author :KevinQ.
Web A little trouble in development
lately , To be exact , It's always a little trouble : Function layer by layer transfer . What does that mean ? For example, a common requirement description is : Record the details of a user's operation .
In the Java Open source framework of jfinal in , Add a user's interface as an example , Yes :
public class XXController() { public void addUser() { // Get operator Integer opUserId = Integer.parseInt(getHeader("opUserId")); // Get other parameters ... service.addUser(...., opUserId); renderAppMsg(" Add user successfully "); }}In order to record the specific operation content and error information added by the user , This record of user actions may need to penetrate good layer methods .
public class XXService() { public void addUser(String tel, String name, String password, Integer opUserId) { checkTel(tel, opUserId); checkName(name, opUserId); checkPassword(password, opUserId); } public void checkTel(String tel, Integer opUserId) { check(tel, opUserId); } publc void check(..., Integer opUserId) { // ... }}This example may not be very appropriate , But I believe you can understand where the trouble lies .
This parameter is not required for each method in the function call chain , It may just be to pass this parameter to the next called function .
So is there a way to help us not need to pass layer by layer , So as to obtain the method of interface request parameters .
reflection
This is a bit like a global variable , But this variable changes for each request , So is there a way for us to save such a : Global variables for each request Well ?
I've been learning recently Shiro In the process of , And the process of learning ruoyi open source framework , We found that they all use a powerful Java class :ThreadLocal.
shiro Use ThreadLocal Is used to save the current login object , If in the frame , The paging plug-in used PageUtil Use ThreadLocal Save... In the request parameters pageNum And pageSize Equal page parameters . So can we also use ThreadLocal To achieve the same purpose .
Use in interceptor ThreadLocal Staging request parameters
So , Let's try , adopt ThreadLocal Save request parameters , Through the interceptor, we can intercept every request , The following is the implementation method :
package com.holdoa.core.interceptor;import com.jfinal.aop.Interceptor;import com.jfinal.aop.Invocation;import javax.servlet.http.HttpServletRequest;public class RequestPool implements Interceptor { public static ThreadLocal<HttpServletRequest> localRequest= new ThreadLocal<>(); @Override public void intercept(Invocation inv) { localRequest.set(inv.getController().getRequest()); inv.invoke(); localRequest.remove(); } public static HttpServletRequest getRequest() { return localRequest.get(); }}We go through ThreadLocal Staging the entire request , Of course , To save memory , You can also save only common parameters that are frequently used , For example, the information of the current login person, etc .
Using parameter
When using , We only need to take the value of the thread local variable :
String para = RequestPool.localRequest.get().getParameter("username");such , We can process each request , No need to Controller as well as Service The method in passes values layer by layer , You only need to take the value directly through the local variable .
Click to follow , The first time to learn about Huawei's new cloud technology ~
边栏推荐
- OneNote 深度评测:使用资源、插件、模版
- HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother
- 966 minimum path sum
- SQL:存储过程和触发器~笔记
- Absolute primes (C language)
- 首批入选!腾讯安全天御风控获信通院业务安全能力认证
- js之遍历数组、字符串
- [MySQL] basic use of cursor
- Sdl2 source analysis 7: performance (sdl_renderpresent())
- document.write()的用法-写入文本——修改样式、位置控制
猜你喜欢

This year, Jianzhi Tencent

愛可可AI前沿推介(7.6)

缓存更新策略概览(Caching Strategies Overview)

After working for 5 years, this experience is left when you reach P7. You have helped your friends get 10 offers

Fastjson parses JSON strings (deserialized to list, map)

OneNote in-depth evaluation: using resources, plug-ins, templates

Aiko ai Frontier promotion (7.6)

The biggest pain point of traffic management - the resource utilization rate cannot go up
![[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics](/img/2d/9a7e88fb774984d061538e3ad4a96b.png)
[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
![[redis design and implementation] part I: summary of redis data structure and objects](/img/2e/b147aa1e23757519a5d049c88113fe.png)
[redis design and implementation] part I: summary of redis data structure and objects
随机推荐
Technology sharing | packet capturing analysis TCP protocol
968 edit distance
document. Usage of write () - write text - modify style and position control
跨分片方案 总结
It's almost the new year, and my heart is lazy
KDD 2022 | 通过知识增强的提示学习实现统一的对话式推荐
JS学习笔记-OO创建怀疑的对象
HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother
数据湖(八):Iceberg数据存储格式
Notes - detailed steps of training, testing and verification of yolo-v4-tiny source code
快过年了,心也懒了
El table table - get the row and column you click & the sort of El table and sort change, El table column and sort method & clear sort clearsort
Why does MySQL index fail? When do I use indexes?
[in depth learning] pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs
Z function (extended KMP)
分糖果
One line by line explanation of the source code of anchor free series network yolox (a total of ten articles, you can change the network at will after reading it, if you won't complain to me)
中国白酒的5场大战
Quick access to video links at station B
MLP (multilayer perceptron neural network) is a multilayer fully connected neural network model.