当前位置:网站首页>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 ~
边栏推荐
- Maximum likelihood estimation and cross entropy loss
- Distributed ID
- 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
- Jupyter launch didn't respond after Anaconda was installed & the web page was opened and ran without execution
- Summary of different configurations of PHP Xdebug 3 and xdebug2
- 【每周一坑】计算100以内质数之和 +【解答】输出三角形
- Web security - payload
- C language operators
- Kubernetes learning summary (20) -- what is the relationship between kubernetes and microservices and containers?
- Leetcode question 448 Find all missing numbers in the array
猜你喜欢
Application layer of tcp/ip protocol cluster
Core principles of video games
PHP online examination system version 4.0 source code computer + mobile terminal
B-jiege's tree (pressed tree DP)
OLED屏幕的使用
Basic knowledge of lists
(工作记录)2020年3月11日至2021年3月15日
Detailed introduction of distributed pressure measurement system VIII: basic introduction of akka actor model
(work record) March 11, 2020 to March 15, 2021
Utilisation de l'écran OLED
随机推荐
SSO single sign on
01 basic introduction - concept nouns
APS taps home appliance industry into new growth points
2022 portal crane driver registration examination and portal crane driver examination materials
Can novices speculate in stocks for 200 yuan? Is the securities account given by qiniu safe?
知识图谱构建流程步骤详解
Distributed ID
Review questions of anatomy and physiology · VIII blood system
Leetcode question 448 Find all missing numbers in the array
Pycharm remote execution
Utilisation de l'écran OLED
“罚点球”小游戏
1500万员工轻松管理,云原生数据库GaussDB让HR办公更高效
In line elements are transformed into block level elements, and display transformation and implicit transformation
设计你的安全架构OKR
Logic is a good thing
Deep learning classification network -- zfnet
Intel 48 core new Xeon run point exposure: unexpected results against AMD zen3 in 3D cache
Initial experience of addresssanitizer Technology
Entity alignment two of knowledge map