springboot 使用ThreadLocal的实例代码
springboot 使用threadlocal
本文参考慕课教程给出一个在spring boot中使用threadlocal实现线程封闭的实例。
首先创建一个包含threadlocal成员变量的实例:
public class requestholder { private final static threadlocal<long> requestholder = new threadlocal<>(); public static void add(long id) { requestholder.set(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.responsebody; @controller @requestmapping("/threadlocal") public class threadlocalcontroller { @requestmapping("/test") @responsebody public long test() { return requestholder.getid(); } }
编写过滤器,在请求到达servlet之前(请求->tomcat容器->filter->servlet->inteceptor->controller),将当前线程的id添加到threadlocal中:
import com.mmall.concurrency.example.threadlocal.requestholder; import lombok.extern.slf4j.slf4j; import javax.servlet.filter; import javax.servlet.filterchain; import javax.servlet.filterconfig; import javax.servlet.servletexception; import javax.servlet.servletrequest; import javax.servlet.servletresponse; import javax.servlet.http.httpservletrequest; import java.io.ioexception; @slf4j public class httpfilter implements filter { @override public void init(filterconfig filterconfig) throws servletexception { } @override public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception { httpservletrequest request = (httpservletrequest) servletrequest; log.info("do filter, {}, {}", thread.currentthread().getid(), request.getservletpath()); //在threadlocal中添加当前线程的id requestholder.add(thread.currentthread().getid()); filterchain.dofilter(servletrequest, servletresponse); } @override public void destroy() { } }
编写拦截器,当请求处理完成后(从controller返回后),清除threadlocal中的id,避免内存泄漏。
import com.mmall.concurrency.example.threadlocal.requestholder; import lombok.extern.slf4j.slf4j; import org.springframework.web.servlet.handler.handlerinterceptoradapter; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; @slf4j public class httpinterceptor extends handlerinterceptoradapter { @override public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception { log.info("prehandle"); return true; } @override public void aftercompletion(httpservletrequest request, httpservletresponse response, 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.servlet.filterregistrationbean; import org.springframework.context.annotation.bean; import org.springframework.web.servlet.config.annotation.interceptorregistry; import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; @springbootapplication public class concurrencyapplication extends webmvcconfigureradapter{ public static void main(string[] args) { springapplication.run(concurrencyapplication.class, args); } @bean public filterregistrationbean httpfilter() { filterregistrationbean registrationbean = new filterregistrationbean(); registrationbean.setfilter(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.tomcatembeddedservletcontainer : tomcat started on port(s): 8080 (http)
2018-11-09 11:16:51.290 info 34076 --- [ main] c.m.concurrency.concurrencyapplication : started concurrencyapplication in 1.718 seconds (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 spring frameworkservlet 'dispatcherservlet'
2018-11-09 11:17:03.060 info 34076 --- [nio-8080-exec-2] o.s.web.servlet.dispatcherservlet : frameworkservlet 'dispatcherservlet': initialization started
2018-11-09 11:17:03.072 info 34076 --- [nio-8080-exec-2] o.s.web.servlet.dispatcherservlet : frameworkservlet 'dispatcherservlet': 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使用中的坑
threadlocal 适用于变量在线程间隔离,而在方法或类间共享的场景。现在在springboot中我做如下场景的使用:
使用 spring boot 创建一个 web 应用程序,使用 threadlocal 存放一个 integer 的值,来暂且代表需要在线程中保存的用户信息,这个值初始是 null。在业务逻辑中,我先从 threadlocal 获取一次值,然后把外部传入的参数设置到 threadlocal 中,来模拟从当前上下文获取到用户信息的逻辑,随后再获取一次值,最后输出两次获得的值和线程名称。
@restcontroller public class threadlocal { private threadlocal<integer> currentuser = threadlocal.withinitial(() -> null); @requestmapping("wrong") public map wrong(@requestparam("userid") integer userid) { //设置用户信息之前先查询一次threadlocal中的用户信息 string before = thread.currentthread().getname() + ":" + currentuser.get(); //设置用户信息到threadlocal currentuser.set(userid); //设置用户信息之后再查询一次threadlocal中的用户信息 string after = thread.currentthread().getname() + ":" + currentuser.get(); //汇总输出两次查询结果 map result = new hashmap(); result.put("before", before); result.put("after", after); return result; } }
为了让问题快速的重现,我在配置文件中设置一下 tomcat 的参数,把工作线程池最大线程数设置为 1,这样始终是同一个线程在处理请求:
server.tomcat.max-threads=1
运行程序后先让用户 1 来请求接口,可以看到第一和第二次获取到用户 id 分别是 null 和 1,符合预期:随后用户 2 来请求接口,这次就出现了 bug,第一和第二次获取到用户 id 分别是 1 和 2,显然第一次获取到了用户 1 的信息,原因就是 tomcat 的线程池重用了线程。
在 tomcat 这种 web 服务器下跑的业务代码,本来就运行在一个多线程环境中,并不能认为没有显式开启多线程就不会有线程安全问题,所以使用类似 threadlocal 工具来存放一些数据时,需要特别注意在代码运行完后,显式地去清空设置的数据。如果在代码中使用了自定义的线程池,也同样会遇到这个问题。修改后代码如下:
@restcontroller public class threadlocal { private threadlocal<integer> currentuser = threadlocal.withinitial(() -> null); @requestmapping("wrong") public map wrong(@requestparam("userid") integer userid) { //设置用户信息之前先查询一次threadlocal中的用户信息 string before = thread.currentthread().getname() + ":" + currentuser.get(); //设置用户信息到threadlocal currentuser.set(userid); try { //设置用户信息之后再查询一次threadlocal中的用户信息 string after = thread.currentthread().getname() + ":" + currentuser.get(); //汇总输出两次查询结果 map result = new hashmap(); result.put("before", before); result.put("after", after); return result; } finally { //增加移除处理 currentuser.remove(); } } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。