当前位置:网站首页>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 ~
边栏推荐
- 039. (2.8) thoughts in the ward
- 审稿人dis整个研究方向已经不仅仅是在审我的稿子了怎么办?
- 代理和反向代理
- c#使用oracle存储过程获取结果集实例
- Description of web function test
- Start the embedded room: system startup with limited resources
- [Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)
- 首批入选!腾讯安全天御风控获信通院业务安全能力认证
- Z function (extended KMP)
- El table table - sortable sorting & disordered sorting when decimal and% appear
猜你喜欢
3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
防火墙基础之外网服务器区部署和双机热备
爱可可AI前沿推介(7.6)
Is it profitable to host an Olympic Games?
Set up a time server
Opencv learning example code 3.2.3 image binarization
愛可可AI前沿推介(7.6)
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
The biggest pain point of traffic management - the resource utilization rate cannot go up
OneNote 深度评测:使用资源、插件、模版
随机推荐
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
【力扣刷题】一维动态规划记录(53零钱兑换、300最长递增子序列、53最大子数组和)
3D人脸重建:从基础知识到识别/重建方法!
基于深度学习的参考帧生成
面试官:Redis中有序集合的内部实现方式是什么?
[interpretation of the paper] machine learning technology for Cataract Classification / classification
Z function (extended KMP)
在最长的距离二叉树结点
2022 fields Award Announced! The first Korean Xu Long'er was on the list, and four post-80s women won the prize. Ukrainian female mathematicians became the only two women to win the prize in history
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
Redistemplate common collection instructions opsforset (V)
首批入选!腾讯安全天御风控获信通院业务安全能力认证
3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
966 minimum path sum
ROS error: could not find a package configuration file provided by "move_base“
Swagger UI tutorial API document artifact
JS traversal array and string
[go][转载]vscode配置完go跑个helloworld例子
启动嵌入式间:资源有限的系统启动
[Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)