当前位置:网站首页>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 20:43: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 ~
边栏推荐
- PHP online examination system version 4.0 source code computer + mobile terminal
- Initial experience of addresssanitizer Technology
- OLED屏幕的使用
- SQL injection 2
- How to turn a multi digit number into a digital list
- What programming do children learn?
- Force deduction brush question - 98 Validate binary search tree
- 解剖生理学复习题·VIII血液系统
- Intel 48 core new Xeon run point exposure: unexpected results against AMD zen3 in 3D cache
- 02 基础入门-数据包拓展
猜你喜欢

Maximum likelihood estimation and cross entropy loss

新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀

小孩子学什么编程?

Laravel笔记-自定义登录中新增登录5次失败锁账户功能(提高系统安全性)

知识图谱构建流程步骤详解

JMeter server resource indicator monitoring (CPU, memory, etc.)

The mail command is used in combination with the pipeline command statement

【OpenCV 例程200篇】220.对图像进行马赛克处理

B-jiege's tree (pressed tree DP)

Variable star --- article module (1)
随机推荐
[asp.net core] set the format of Web API response data -- formatfilter feature
Core principles of video games
Variable star --- article module (1)
Minimum cut edge set of undirected graph
15 millions d'employés sont faciles à gérer et la base de données native du cloud gaussdb rend le Bureau des RH plus efficace
Rhcsa Road
Redis insert data garbled solution
Common doubts about the introduction of APS by enterprises
【每周一坑】输出三角形
Maximum likelihood estimation and cross entropy loss
8086 instruction code summary (table)
Discussion on beegfs high availability mode
棋盘左上角到右下角方案数(2)
Database - how to get familiar with hundreds of tables of the project -navicat these unique skills, have you got it? (exclusive experience)
Pycharm remote execution
Leetcode hot topic Hot 100 day 32: "minimum coverage substring"
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
RT thread I2C tutorial
What programming do children learn?
为什么新手在编程社区提问经常得不到回答,甚至还会被嘲讽?