亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2017年03月22日 09:46:53   作者:三劫散仙  
本篇文章主要介紹了詳解Spring-Boot中如何使用多線程處理任務(wù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。

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

比如如下場(chǎng)景:

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

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

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

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

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

@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: {}啟動(dòng) !",(i+1),list.get(i).getName());
    }

  }


}

最后備忘下logback.xml,里面可以配置相對(duì)和絕對(duì)的日志文件路徑:

<!-- 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)是相對(duì)路徑 -->
   <fileNamePattern>logs/xalert-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
    <!--<property name="logDir" value="E:/testlog" />-->
    <!--絕對(duì)路徑定義-->
   <!--<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>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。 

相關(guān)文章

  • IDEA的spring項(xiàng)目使用@Qualifier飄紅問(wèn)題及解決

    IDEA的spring項(xiàng)目使用@Qualifier飄紅問(wèn)題及解決

    這篇文章主要介紹了IDEA的spring項(xiàng)目使用@Qualifier飄紅問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Java MyBatis可視化代碼生成工具使用教程

    Java MyBatis可視化代碼生成工具使用教程

    這篇文章主要介紹了Java MyBatis可視化代碼生成工具使用教程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Ubuntu 安裝 JDK8 的兩種方法(總結(jié))

    Ubuntu 安裝 JDK8 的兩種方法(總結(jié))

    下面小編就為大家?guī)?lái)一篇Ubuntu 安裝 JDK8 的兩種方法(總結(jié))。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-06-06
  • eclipse老是自動(dòng)跳到console解決辦法

    eclipse老是自動(dòng)跳到console解決辦法

    eclipse啟動(dòng)服務(wù)后,想看一些properties信息或者別的,但老是自動(dòng)跳轉(zhuǎn)到console頁(yè)面,本文給大家介紹了解決辦法,對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-03-03
  • Java反射機(jī)制詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    Java反射機(jī)制詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要為大家詳細(xì)介紹了Java反射機(jī)制的相關(guān)資料,主要包括反射的概念、作用
    2017-06-06
  • 基于Java手寫一個(gè)好用的FTP操作工具類

    基于Java手寫一個(gè)好用的FTP操作工具類

    網(wǎng)上百度了很多FTP的java?工具類,發(fā)現(xiàn)文章代碼都比較久遠(yuǎn),且代碼臃腫,即使搜到了代碼寫的還可以的,封裝的常用操作方法不全面。所以本文將手寫一個(gè)好用的Java?FTP操作工具類,需要的可以參考一下
    2022-04-04
  • Spring?Boot實(shí)現(xiàn)MyBatis動(dòng)態(tài)創(chuàng)建表的操作語(yǔ)句

    Spring?Boot實(shí)現(xiàn)MyBatis動(dòng)態(tài)創(chuàng)建表的操作語(yǔ)句

    這篇文章主要介紹了Spring?Boot實(shí)現(xiàn)MyBatis動(dòng)態(tài)創(chuàng)建表,MyBatis提供了動(dòng)態(tài)SQL,我們可以通過(guò)動(dòng)態(tài)SQL,傳入表名等信息然組裝成建表和操作語(yǔ)句,本文通過(guò)案例講解展示我們的設(shè)計(jì)思路,需要的朋友可以參考下
    2024-01-01
  • Java中RedissonClient基本使用指南

    Java中RedissonClient基本使用指南

    RedissonClient 是一個(gè)強(qiáng)大的 Redis 客戶端,提供了豐富的功能和簡(jiǎn)單的 API,本文就來(lái)介紹一下Java中RedissonClient基本使用指南,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-03-03
  • Spring P標(biāo)簽的使用詳解

    Spring P標(biāo)簽的使用詳解

    這篇文章主要介紹了Spring P標(biāo)簽的使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 使用springboot aop記錄接口請(qǐng)求的參數(shù)及響應(yīng)

    使用springboot aop記錄接口請(qǐng)求的參數(shù)及響應(yīng)

    該文章介紹了如何使用SpringAOP的切面注解,如@Before和@AfterReturning,來(lái)記錄Controller層的方法輸入?yún)?shù)和響應(yīng)結(jié)果,還討論了@Around注解的靈活性,允許在方法執(zhí)行前后進(jìn)行更多控制,需要的朋友可以參考下
    2024-05-05

最新評(píng)論