Spring-Boot中如何使用多线程处理任务
看到这个标题,相信不少人会感到疑惑,回忆你们自己的场景会发现,在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上下文:
/**
* 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);
}
}
然后定义我们的自己的线程类,注意此类是原型作用域,不能是默认的单例:
@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,查看是否是多实例:
/**
* 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方法中启动,下面看下,如何定义组件启动:
@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,里面可以配置相对和绝对的日志文件路径:
<!-- 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
有什么问题可以扫码关注微信公众号:我是攻城师(woshigcs),在后台留言咨询。 技术债不能欠,健康债更不能欠, 求道之路,与君同行。 
Spring-Boot中如何使用多线程处理任务的更多相关文章
- spring boot(三):Spring Boot中Redis的使用
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...
- Spring Boot中的事务管理
原文 http://blog.didispace.com/springboottransactional/ 什么是事务? 我们在开发企业应用时,对于业务人员的一个操作实际是对数据读写的多步操作的结合 ...
- Spring Boot中的注解
文章来源:http://www.tuicool.com/articles/bQnMra 在Spring Boot中几乎可以完全弃用xml配置文件,本文的主题是分析常用的注解. Spring最开始是为了 ...
- 在Spring Boot中使用Https
本文介绍如何在Spring Boot中,使用Https提供服务,并将Http请求自动重定向到Https. Https证书 巧妇难为无米之炊,开始的开始,要先取得Https证书.你可以向证书机构申请证书 ...
- Spring Boot中使用Swagger2构建强大的RESTful API文档
由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...
- Dubbo在Spring和Spring Boot中的使用
一.在Spring中使用Dubbo 1.Maven依赖 <dependency> <groupId>com.alibaba</groupId> <artifa ...
- springboot(十一):Spring boot中mongodb的使用
mongodb是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置 ...
- springboot(三):Spring boot中Redis的使用
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...
- Spring Boot中使用Swagger2构建API文档
程序员都很希望别人能写技术文档,自己却很不愿意写文档.因为接口数量繁多,并且充满业务细节,写文档需要花大量的时间去处理格式排版,代码修改后还需要同步修改文档,经常因为项目时间紧等原因导致文档滞后于代码 ...
- Spring Boot中使用 Spring Security 构建权限系统
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...
随机推荐
- plsql初次连接oracle报错解决方案
windows7 64bit Oracle win64 11gR2(两个文件) PL/SQL v9.0 详细错误信息 Initialization error Could not initialize ...
- JVM 简述
JVM(Java Virtual Machine,Java虚拟机) Java程序的跨平台特性主要是指字节码文件可以在任何具有Java虚拟机的计算机或者电子设备上运行,Java虚拟机中的Java解释器负 ...
- 【CF886E】Maximum Element
题目 考虑正难则反,答案即为\(n!-\text{返回值为n的排列数}\) 一个排列的返回值为\(n\),当且仅当在\(n\)出现之前没有一个数后面有连续\(k\)个小于它的数 设\(f_i\)表示\ ...
- windows平板软件开机自启动+霸屏的操作方法
转载(忘了地址) 很好很强大.成功亲测 使用你自己的账号(最好是管理员权限的账号)登录Windows,然后添加一个给其他人使用的账户(假设为other),注意一定要为other设置密码. 运行 ...
- jdk8中map新增的merge方法介绍
1.Map.merge方法介绍 jdk8对于许多常用的类都扩展了一些面向函数,lambda表达式,方法引用的功能,使得java面向函数编程更为方便.其中Map.merge方法就是其中一个,merge方 ...
- where I will go
为什么我选择了java? 作为一个0基础入门的编程小白,大一的时候我接触了C语言,写了我的第一个程序hello world,内心有点小骄傲(我也能编程了),那时候还不知道java是什么,然而实际公司的 ...
- systemctl命令的使用及服务状态的查看
二.systemctl命令 systemctl list-units ##列出当前系统服务的状态 systemctl list-unit-files ##列出服务的开 ...
- JavaScript ---- 原型,原型链(什么是原型)
和“闭包”一样,“原型”这个概念也经常被提起. 其实这个“概念”应该和构造函数,对象放在一起讲,但是由于时间关系,先把这部分抽取出来讲.再讲这个概念时我们先大致了解下JavaScript中的“对象”. ...
- 简单介绍下怎么在spring中使用RabbitMQ
这篇文章主要介绍了简单了解如何在spring中使用RabbitMQ,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 常见的消息中间件产品: (1)Ac ...
- sql语句创建表
create table `search_custom_mall` ( `id` ) NOT NULL PRIMARY KEY AUTO_INCREMENT, `uid` ) NOT NULL, `n ...