首页 > 开发 > Java > 正文

详解Spring-Boot中如何使用多线程处理任务

2024-07-13 10:05:41
字体:
来源:转载
供稿:网友

看到这个标题,相信不少人会感到疑惑,回忆你们自己的场景会发现,在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的上下文 */@Componentpublic 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@285f38f6Thread[Thread-3,5,main] => com.xuele.bigdata.xalert.dao.rule.impl.GreaterDaoImpl@285f38f6Thread[Thread-4,5,main] => com.xuele.bigdata.xalert.dao.rule.impl.GreaterDaoImpl@285f38f6

可以看到我们的监控类是多实例的,它里面的Dao是单实例的,这样以来我们就可以在spring中使用多线程处理我们的任务了。

如何启动我们的多线程任务类,可以专门定义一个组件类启动也可以在启动Spring的main方法中启动,下面看下,如何定义组件启动:

@Componentpublic 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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。 


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表