看到这个标题,相信不少人会感到疑惑,回忆你们自己的场景会发现,在spring的项目中很少有使用多线程处理任务的,没错,大多数时候我们都是使用spring mvc开发的web项目,默认的controller,service,dao组件的作用域都是单实例,无状态,然后被并发多线程调用,那么如果我想使用多线程处理任务,该如何做呢?
比如如下场景:
使用spring-boot开发一个监控的项目,每个被监控的业务(可能是一个数据库表或者是一个pid进程)都会单独运行在一个线程中,有自己配置的参数,总结起来就是:
(1)多实例(多个业务,每个业务相互隔离互不影响)
(2)有状态(每个业务,都有自己的配置参数)
如果是非spring-boot项目,实现起来可能会相对简单点,直接new多线程启动,然后传入不同的参数类即可,在spring的项目中,由于bean对象是spring容器管理的,你直接new出来的对象是没法使用的,就算你能new成功,但是bean里面依赖的其他组件比如dao,是没法初始化的,因为你饶过了spring,默认的spring初始化一个类时,其相关依赖的组件都会被初始化,但是自己new出来的类,是不具备这种功能的,所以我们需要通过spring来获取我们自己的线程类,那么如何通过spring获取类实例呢,需要定义如下的一个类来获取springcontext上下文:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/** * created by administrator on 2016/8/18. * 设置sping的上下文 */ @component public class applicationcontextprovider implements applicationcontextaware { private static applicationcontext context; private applicationcontextprovider(){} @override public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { context = applicationcontext; } public static <t> t getbean(string name, class <t> aclass){ return context.getbean(name,aclass); } } |
然后定义我们的自己的线程类,注意此类是原型作用域,不能是默认的单例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@component ( "mtask" ) @scope ( "prototype" ) public class moniotrtask extends thread { final static logger logger= loggerfactory.getlogger(moniotrtask. class ); //参数封装 private monitor monitor; public void setmonitor(monitor monitor) { this .monitor = monitor; } @resource (name = "greaterdaoimpl" ) private ruledao greaterdaoimpl; @override public void run() { logger.info( "线程:" +thread.currentthread().getname()+ "运行中....." ); } } |
写个测试例子,测试下使用springcontext获取bean,查看是否是多实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/** * created by administrator on 2016/8/18. */ @runwith (springjunit4classrunner. class ) @springboottest (classes =applicationmain. class ) public class spingcontexttest { @test public void show() throws exception{ moniotrtask m1= applicationcontextprovider.getbean( "mtask" , moniotrtask. class ); moniotrtask m2=applicationcontextprovider.getbean( "mtask" , moniotrtask. class ); moniotrtask m3=applicationcontextprovider.getbean( "mtask" , moniotrtask. class ); system.out.println(m1+ " => " +m1.greaterdaoimpl); system.out.println(m2+ " => " +m2.greaterdaoimpl); system.out.println(m3+ " => " +m3.greaterdaoimpl); } } |
运行结果如下:
[ info ] [2016-08-25 17:36:34] com.test.tools.spingcontexttest [57] - started spingcontexttest in 2.902 seconds (jvm running for 4.196)
2016-08-25 17:36:34.842 info 8312 --- [ main] com.test.tools.spingcontexttest : started spingcontexttest in 2.902 seconds (jvm running for 4.196)
thread[thread-2,5,main] => com.xuele.bigdata.xalert.dao.rule.impl.greaterdaoimpl@285f38f6
thread[thread-3,5,main] => com.xuele.bigdata.xalert.dao.rule.impl.greaterdaoimpl@285f38f6
thread[thread-4,5,main] => com.xuele.bigdata.xalert.dao.rule.impl.greaterdaoimpl@285f38f6
可以看到我们的监控类是多实例的,它里面的dao是单实例的,这样以来我们就可以在spring中使用多线程处理我们的任务了。
如何启动我们的多线程任务类,可以专门定义一个组件类启动也可以在启动spring的main方法中启动,下面看下,如何定义组件启动:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@component public class starttask { final static logger logger= loggerfactory.getlogger(starttask. class ); //定义在构造方法完毕后,执行这个初始化方法 @postconstruct public void init(){ final list<monitor> list = parseruleutils.parserules(); logger.info( "监控任务的总task数:{}" ,list.size()); for ( int i= 0 ;i<list.size();i++) { moniotrtask moniotrtask= applicationcontextprovider.getbean( "mtask" , moniotrtask. class ); moniotrtask.setmonitor(list.get(i)); moniotrtask.start(); logger.info( "第{}个监控task: {}启动 !" ,(i+ 1 ),list.get(i).getname()); } } } |
最后备忘下logback.xml,里面可以配置相对和绝对的日志文件路径:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
<!-- logback configuration. see http: //logback.qos.ch/manual/index.html --> <configuration scan= "true" scanperiod= "10 seconds" > <!-- simple file output --> <appender name= "file" class = "ch.qos.logback.core.rolling.rollingfileappender" > <!--<appender name= "stdout" class = "ch.qos.logback.core.consoleappender" >--> <!-- encoder defaults to ch.qos.logback.classic.encoder.patternlayoutencoder --> <encoder> <pattern> [ %-5level] [%date{yyyy-mm-dd hh:mm:ss}] %logger{ 96 } [%line] - %msg%n </pattern> <charset>utf- 8 </charset> <!-- 此处设置字符集 --> </encoder> <rollingpolicy class = "ch.qos.logback.core.rolling.timebasedrollingpolicy" > <!-- rollover daily 配置日志所生成的目录以及生成文件名的规则,默认是相对路径 --> <filenamepattern>logs/xalert-%d{yyyy-mm-dd}.%i.log</filenamepattern> <!--<property name= "logdir" value= "e:/testlog" />--> <!--绝对路径定义--> <!--<filenamepattern>${logdir}/logs/xalert-%d{yyyy-mm-dd}.%i.log</filenamepattern>--> <timebasedfilenamingandtriggeringpolicy class = "ch.qos.logback.core.rolling.sizeandtimebasedfnatp" > <!-- or whenever the file size reaches 64 mb --> <maxfilesize> 64 mb</maxfilesize> </timebasedfilenamingandtriggeringpolicy> </rollingpolicy> <filter class = "ch.qos.logback.classic.filter.thresholdfilter" > <level>debug</level> </filter> <!-- safely log to the same file from multiple jvms. degrades performance! --> <prudent> true </prudent> </appender> <!-- console output --> <appender name= "stdout" class = "ch.qos.logback.core.consoleappender" > <!-- encoder defaults to ch.qos.logback.classic.encoder.patternlayoutencoder --> <encoder> <pattern> [ %-5level] [%date{yyyy-mm-dd hh:mm:ss}] %logger{ 96 } [%line] - %msg%n </pattern> <charset>utf- 8 </charset> <!-- 此处设置字符集 --> </encoder> <!-- only log level warn and above --> <filter class = "ch.qos.logback.classic.filter.thresholdfilter" > <level>info</level> </filter> </appender> <!-- enable file and stdout appenders for all log messages. by default , only log at level info and above. --> <root level= "info" > <appender-ref ref= "stdout" /> <appender-ref ref= "file" /> </root> <!-- for loggers in the these namespaces, log at all levels. --> <logger name= "pedestal" level= "all" /> <logger name= "hammock-cafe" level= "all" /> <logger name= "user" level= "all" /> <include resource= "org/springframework/boot/logging/logback/base.xml" /> <jmxconfigurator/> </configuration> |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/qindongliang/p/5808145.html