本文参考慕课教程给出一个在spring boot中使用threadlocal实现线程封闭的实例。
首先创建一个包含threadlocal成员变量的实例:
public class requestholder { private final static threadlocal<long> requestholder = new threadlocal<>(); public static void add(long id) { requestholder.t(id); } public static long getid() { return requestholder.get(); } public static void remove() { requestholder.remove(); }}
编写一个controller类,请求该类的test()方法获取threadlocal中存储的id:
import org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.responbody; @controller@requestmapping("/threadlocal")public class threadlocalcontroller { @requestmapping("/test") @responbody public long test() { return requestholder.getid(); }}
编写过滤器,在请求到达rvlet之前(请求->tomcat容器->filter->rvlet->inteceptor->controller),将当前线程的id添加到threadlocal中:
import com.mmall.concurrency.example.threadlocal.requestholder;import lombok.extern.slf4j.slf4j; import javax.rvlet.filter;import javax.rvlet.filterchain;import javax.rvlet.filterconfig;import javax.rvlet.rvletexception;import javax.rvlet.rvletrequest;import javax.rvlet.rvletrespon;import javax.rvlet.http.httprvletrequest;import java.io.ioexception; @slf4jpublic class httpfilter implements filter { @override public void init(filterconfig filterconfig) throws rvletexception { } @override public void dofilter(rvletrequest rvletrequest, rvletrespon rvletrespon, filterchain filterchain) throws ioexception, rvletexception { httprvletrequest request = (httprvletrequest) rvletrequest; log.info("do filter, {}, {}", thread.currentthread().getid(), request.getrvletpath()); //在threadlocal中添加当前线程的id requestholder.add(thread.currentthread().getid()); filterchain.dofilter(rvletrequest, rvletrespon); } @override public void destroy() { }}
编写拦截器,当请求处理完成后(从controller返回后),清除threadlocal中的id,避免内存泄漏。
import com.mmall.concurrency.example.threadlocal.requestholder;import lombok.extern.slf4j.slf4j;import org.springframework.web.rvlet.handler.handlerinterceptoradapter; import javax.rvlet.http.httprvletrequest;import javax.rvlet.http.httprvletrespon; @slf4jpublic class httpinterceptor extends handlerinterceptoradapter { @override public boolean prehandle(httprvletrequest request, httprvletrespon respon, object handler) throws exception { log.info("prehandle"); return true; } @override public void aftercompletion(httprvletrequest request, httprvletrespon respon, object handler, exception ex) throws exception { log.info("threadid:"+requestholder.getid()); requestholder.remove(); log.info("aftercompletion"); return; }}
最后,我们需要在spring boot启动类上注册我们定义的filer及inteceptor,并设置拦截路径。
import org.springframework.boot.springapplication;import org.springframework.boot.autoconfigure.springbootapplication;import org.springframework.boot.web.rvlet.filterregistrationbean;import org.springframework.context.annotation.bean;import org.springframework.web.rvlet.config.annotation.interceptorregistry;import org.springframework.web.rvlet.config.annotation.webmvcconfigureradapter; @springbootapplicationpublic class concurrencyapplication extends webmvcconfigureradapter{ public static void main(string[] args) { springapplication.run(concurrencyapplication.class, args); } @bean public filterregistrationbean httpfilter() { filterregistrationbean registrationbean = new filterregistrationbean(); registrationbean.tfilter(new httpfilter()); registrationbean.addurlpatterns("/threadlocal/*"); return registrationbean; } @override public void addinterceptors(interceptorregistry registry) { registry.addinterceptor(new httpinterceptor()).addpathpatterns("/**"); }}
在浏览器或者postman中输入http://localhost:8080/threadlocal/test
观察输出结果:
2018-11-09 11:16:51.287 info 34076 — [ main] s.b.c.e.t.tomcatembeddedrvletcontainer : tomcat started on port(s): 808真实故事0 (http)
2018-11-09 11:16:51.290 info 34076 — [ main] c.m.concurrency.concurrencyapplication : started concurrencyapplication in 1.718 conds (jvm running for 2.132)
2018-11-09 11:17:03.060 info 34076 — [nio-8080-exec-2] o.a.c.c.c.[tomcat].[localhost].[/] : initializing sp我有三个母亲ring frameworkrvlet ‘dispatchers日本童话ervlet’
2018-11-09 11:17:03.060 info 34076 — [nio-8080-exec-2] o.s.web.rvlet.dispatcherrvlet : frameworkrvlet ‘dispatcherrvlet’: initialization started
2018-11-09 11:17:03.072 info 34076 — [nio-8080-exec-2] o.s.web.rvlet.dispatcherrvlet : frameworkrvlet ‘dispatcherrvlet’: initialization completed in 12 ms
2018-11-09 11:17:03.078 info 34076 — [nio-8080-exec-2] com.mmall.concurrency.httpfilter : do filter, 29, /threadlocal/test
2018-11-09 11:17:03.090 info 34076 — [nio-8080-exec-2] com.mmall.concurrency.httpinterceptor : prehandle
2018-11-09 11:17:03.124 info 34076 — [nio-8080-exec-2] com.mmall.concurrency.httpinterceptor : threadid:29
2018-11-09 11:17:03.124 info 34076 — [nio-8080-exec-2] com.mmall.concurrency.httpinterceptor : aftercompletion
从打印的日志结果中,我们看到在filter中我们将当前线程的id 29添加到了threadlocal中,随后在inteceptor中打印并删除了id。
threadlocal 适用于变量在线程间隔离,而在方法或类间共享的场景。现在在springboot中我做如下场景的使用:
使用 spring boot 创建一个 web 应用程序,使用 threadlocal 存放一个 integer 的值,来暂且代表需要在线程中保存的用户信息,这个值初始是 null。在业务逻辑中,我先从 threadlocal 获取一次值,然后把外部传入的参数设置到 threadlocal 中,来模拟从当前上下文获取到用户信息的逻辑,随后再获取一次值,最后输出两次获得的值和线文化课辅导班程名称。
@restcontrollerpublic class threadlocal { private threadlocal<integer> currentur = threadlocal.withinitial(() -> null); @requestmapping("wrong") public map wrong(@requestparam("urid") integer urid) { //设置用户信息之前先查询一次threadlocal中的用户信息 string before = thread.currentthread().getname() + ":" + currentur.get(); //设置用户信息到threadlocal currentur.t(urid); //设置用户信息之后再查询一次threadlocal中的用户信息 string after = thread.currentthread().getname() + ":" + currentur.get(); //汇总输出两次查询结果 map result = new hashmap(); result.put("before", before); result.put("after", after); return result; }}
为了让问题快速的重现,我在配置文件中设置一下 tomcat 的参数,把工作线程池最大线程数设置为 1,这样始终是同一个线程在处理请求:
rver.tomcat.max-threads=1
运行程序后先让用户 1 来请求接口,可以看到第一和第二次获取到用户 id 分别是 null 和 1,符合预期:随后用户 2 来请求接口,这次就出现了 bug,第一和第二次获取到用户 id 分别是 1 和 2,显然第一次获取到了用户 1 的信息,原因就是 tomcat 的线程池重用了线程。
在 tomcat 这种 web 服务器下跑的业务代码,本来就运行在一个多线程环境中,并不能认为没有显式开启多线程就不会有线程安全问题,所以使用类似 threadlocal 工具来存放一些数据时,需要特别注意在代码运行完后,显式地去清空设置的数据。如果在代码中使用了自定义的线程池,也同样会遇到这个问题。修改后陈政事疏代码如下:
@restcontrollerpublic class threadlocal { private threadlocal<integer> currentur = threadlocal.withinitial(() -> null); @requestmapping("wrong") public map wrong(@requestparam("urid") integer urid) { //设置用户信息之前先查询一次threadlocal中的用户信息 string before = thread.currentthread().getname() + ":" + currentur.get(); //设置用户信息到threadlocal currentur.t(urid); try { //设置用户信息之后再查询一次threadlocal中的用户信息 string after = thread.currentthread().getname() + ":" + currentur.get(); //汇总输出两次查询结果 map result = new hashmap(); result.put("before", before); result.put("after", after); return result; } finally { //增加移除处理 currentur.remove(); } }}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。
本文发布于:2023-04-04 01:09:38,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/0cc1c6b4a3c4e28dcc674eb21be74e8a.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:springboot 使用ThreadLocal的实例代码.doc
本文 PDF 下载地址:springboot 使用ThreadLocal的实例代码.pdf
留言与评论(共有 0 条评论) |