溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring-Boot中如何使用多線程處理任務(wù)方法

發(fā)布時(shí)間:2020-09-12 01:07:31 來源:腳本之家 閱讀:138 作者:三劫散仙 欄目:編程語言

看到這個(gè)標(biāo)題,相信不少人會感到疑惑,回憶你們自己的場景會發(fā)現(xiàn),在Spring的項(xiàng)目中很少有使用多線程處理任務(wù)的,沒錯(cuò),大多數(shù)時(shí)候我們都是使用Spring MVC開發(fā)的web項(xiàng)目,默認(rèn)的Controller,Service,Dao組件的作用域都是單實(shí)例,無狀態(tài),然后被并發(fā)多線程調(diào)用,那么如果我想使用多線程處理任務(wù),該如何做呢?

比如如下場景:

使用spring-boot開發(fā)一個(gè)監(jiān)控的項(xiàng)目,每個(gè)被監(jiān)控的業(yè)務(wù)(可能是一個(gè)數(shù)據(jù)庫表或者是一個(gè)pid進(jìn)程)都會單獨(dú)運(yùn)行在一個(gè)線程中,有自己配置的參數(shù),總結(jié)起來就是:

(1)多實(shí)例(多個(gè)業(yè)務(wù),每個(gè)業(yè)務(wù)相互隔離互不影響)

(2)有狀態(tài)(每個(gè)業(yè)務(wù),都有自己的配置參數(shù))

如果是非spring-boot項(xiàng)目,實(shí)現(xiàn)起來可能會相對簡單點(diǎn),直接new多線程啟動,然后傳入不同的參數(shù)類即可,在spring的項(xiàng)目中,由于Bean對象是spring容器管理的,你直接new出來的對象是沒法使用的,就算你能new成功,但是bean里面依賴的其他組件比如Dao,是沒法初始化的,因?yàn)槟沭堖^了spring,默認(rèn)的spring初始化一個(gè)類時(shí),其相關(guān)依賴的組件都會被初始化,但是自己new出來的類,是不具備這種功能的,所以我們需要通過spring來獲取我們自己的線程類,那么如何通過spring獲取類實(shí)例呢,需要定義如下的一個(gè)類來獲取SpringContext上下文:

/**
 * Created by Administrator on 2016/8/18.
 * 設(shè)置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);
 }
}

然后定義我們的自己的線程類,注意此類是原型作用域,不能是默認(rèn)的單例:

@Component("mTask")
@Scope("prototype")
public class MoniotrTask extends Thread {

 final static Logger logger= LoggerFactory.getLogger(MoniotrTask.class);
 //參數(shù)封裝
 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()+"運(yùn)行中.....");
 }

}

寫個(gè)測試?yán)?,測試下使用SpringContext獲取Bean,查看是否是多實(shí)例:

/**
 * 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);

 }


}

運(yùn)行結(jié)果如下:

[ 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

可以看到我們的監(jiān)控類是多實(shí)例的,它里面的Dao是單實(shí)例的,這樣以來我們就可以在spring中使用多線程處理我們的任務(wù)了。

如何啟動我們的多線程任務(wù)類,可以專門定義一個(gè)組件類啟動也可以在啟動Spring的main方法中啟動,下面看下,如何定義組件啟動:

@Component
public class StartTask {

 final static Logger logger= LoggerFactory.getLogger(StartTask.class);
 
 //定義在構(gòu)造方法完畢后,執(zhí)行這個(gè)初始化方法
 @PostConstruct
 public void init(){

  final List<Monitor> list = ParseRuleUtils.parseRules();
  logger.info("監(jiān)控任務(wù)的總Task數(shù):{}",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("第{}個(gè)監(jiān)控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> <!-- 此處設(shè)置字符集 -->
 </encoder>

 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  <!-- rollover daily 配置日志所生成的目錄以及生成文件名的規(guī)則,默認(rèn)是相對路徑 -->
  <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> <!-- 此處設(shè)置字符集 -->
  </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>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI