欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

比如如下場景:

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

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

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

如果是非spring-boot項目,實現(xiàn)起來可能會相對簡單點,直接new多線程啟動,然后傳入不同的參數(shù)類即可,在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);
  //參數(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()+"運行中.....");
  }

}

寫個測試例子,測試下使用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

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

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

@Component
public class StartTask  {

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

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

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。 

相關文章

  • IDEA的spring項目使用@Qualifier飄紅問題及解決

    IDEA的spring項目使用@Qualifier飄紅問題及解決

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

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

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

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

    下面小編就為大家?guī)硪黄猆buntu 安裝 JDK8 的兩種方法(總結)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • eclipse老是自動跳到console解決辦法

    eclipse老是自動跳到console解決辦法

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

    Java反射機制詳解_動力節(jié)點Java學院整理

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

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

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

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

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

    Java中RedissonClient基本使用指南

    RedissonClient 是一個強大的 Redis 客戶端,提供了豐富的功能和簡單的 API,本文就來介紹一下Java中RedissonClient基本使用指南,具有一定的參考價值,感興趣的可以了解一下
    2024-03-03
  • Spring P標簽的使用詳解

    Spring P標簽的使用詳解

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

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

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

最新評論