您好,登錄后才能下訂單哦!
看到這個(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ù)類(lèi)即可,在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è)類(lèi)時(shí),其相關(guān)依賴的組件都會(huì)被初始化,但是自己new出來(lái)的類(lèi),是不具備這種功能的,所以我們需要通過(guò)spring來(lái)獲取我們自己的線程類(lèi),那么如何通過(guò)spring獲取類(lèi)實(shí)例呢,需要定義如下的一個(gè)類(lèi)來(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); } }
然后定義我們的自己的線程類(lèi),注意此類(lèi)是原型作用域,不能是默認(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)行中....."); } }
寫(xiě)個(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)控類(lèi)是多實(shí)例的,它里面的Dao是單實(shí)例的,這樣以來(lái)我們就可以在spring中使用多線程處理我們的任務(wù)了。
如何啟動(dòng)我們的多線程任務(wù)類(lèi),可以專門(mén)定義一個(gè)組件類(lèi)啟動(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í)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。