当前位置:网站首页>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 ~
边栏推荐
- Initial experience of addresssanitizer Technology
- Discussion on beegfs high availability mode
- Rhcsa Road
- 使用.Net驱动Jetson Nano的OLED显示屏
- Detailed explanation of knowledge map construction process steps
- Value of APS application in food industry
- 为什么新手在编程社区提问经常得不到回答,甚至还会被嘲讽?
- Rhcsa Road
- 硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件
- 8086 instruction code summary (table)
猜你喜欢
##无yum源安装spug监控
知识图谱构建流程步骤详解
全网最全的知识库管理工具综合评测和推荐:FlowUs、Baklib、简道云、ONES Wiki 、PingCode、Seed、MeBox、亿方云、智米云、搜阅云、天翎
Tencent T4 architect, Android interview Foundation
02 basic introduction - data package expansion
Detailed introduction of distributed pressure measurement system VIII: basic introduction of akka actor model
use. Net drives the OLED display of Jetson nano
The mail command is used in combination with the pipeline command statement
OLED屏幕的使用
使用.Net分析.Net达人挑战赛参与情况
随机推荐
【每周一坑】输出三角形
Solution to the 38th weekly match of acwing
Simple continuous viewing PTA
Boder radius has four values, and boder radius exceeds four values
【每周一坑】正整数分解质因数 +【解答】计算100以内质数之和
JS implementation force deduction 71 question simplified path
Pytest (3) - Test naming rules
Minimum cut edge set of undirected graph
Special topic of rotor position estimation of permanent magnet synchronous motor -- fundamental wave model and rotor position angle
Function optimization and arrow function of ES6
Mécanisme de fonctionnement et de mise à jour de [Widget Wechat]
8086 instruction code summary (table)
Jupyter launch didn't respond after Anaconda was installed & the web page was opened and ran without execution
02 基础入门-数据包拓展
[weekly pit] calculate the sum of primes within 100 + [answer] output triangle
Leetcode question 448 Find all missing numbers in the array
Tencent byte Alibaba Xiaomi jd.com offer got a soft hand, and the teacher said it was great
Recyclerview GridLayout bisects the middle blank area
Intel 48 core new Xeon run point exposure: unexpected results against AMD zen3 in 3D cache
1500万员工轻松管理,云原生数据库GaussDB让HR办公更高效