Spring-Boot中如何使用多線程處理任務(wù)方法
看到這個(gè)標(biāo)題,相信不少人會(huì)感到疑惑,回憶你們自己的場景會(huì)發(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)程)都會(huì)單獨(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)起來可能會(huì)相對(duì)簡單點(diǎn),直接new多線程啟動(dòng),然后傳入不同的參數(shù)類即可,在spring的項(xiàng)目中,由于Bean對(duì)象是spring容器管理的,你直接new出來的對(duì)象是沒法使用的,就算你能new成功,但是bean里面依賴的其他組件比如Dao,是沒法初始化的,因?yàn)槟沭堖^了spring,默認(rèn)的spring初始化一個(gè)類時(shí),其相關(guān)依賴的組件都會(huì)被初始化,但是自己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ù)了。
如何啟動(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>
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java使用位運(yùn)算實(shí)現(xiàn)加減乘除詳解
這篇文章主要為大家詳細(xì)介紹了Java如何使用位運(yùn)算實(shí)現(xiàn)加減乘除,文中的示例代碼講解詳細(xì),對(duì)我們深入了解Java有一定的幫助,感興趣的可以了解一下2023-05-05
一篇文章帶你深入理解JVM虛擬機(jī)讀書筆記--鎖優(yōu)化
這篇文章深入介紹了JVM虛擬機(jī)的鎖優(yōu)化,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2021-09-09
Java實(shí)現(xiàn)提取HTML文件中的文本內(nèi)容
從?HTML?文件中提取文本內(nèi)容是數(shù)據(jù)抓取中的一個(gè)常見任務(wù),本文主要和大家分享了如何使用免費(fèi)?Java?API?從HTML?文件中提取文本內(nèi)容,需要的可以參考下2024-04-04
Spring Cloud入門教程之Zuul實(shí)現(xiàn)API網(wǎng)關(guān)與請(qǐng)求過濾
這篇文章主要給大家介紹了關(guān)于Spring Cloud入門教程之Zuul實(shí)現(xiàn)API網(wǎng)關(guān)與請(qǐng)求過濾的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-05-05

