看到這個標題,相信很多人會感到疑惑,回憶大家本身的場景會發現,在Spring的項目中不多有使用多線程處理任務的,沒錯,大多數時候咱們都是使用Spring MVC開發的web項目,默認的Controller,Service,Dao組件的做用域都是單實例,無狀態,而後被併發多線程調用,那麼若是我想使用多線程處理任務,該如何作呢?html
好比以下場景:java
使用spring-boot開發一個監控的項目,每一個被監控的業務(多是一個數據庫表或者是一個pid進程)都會單獨運行在一個線程中,有本身配置的參數,總結起來就是:web
(1)多實例(多個業務,每一個業務相互隔離互不影響)spring
(2)有狀態(每一個業務,都有本身的配置參數)數據庫
若是是非spring-boot項目,實現起來可能會相對簡單點,直接new多線程啓動,而後傳入不一樣的參數類便可,在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); //參數封裝 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); } }
運行結果以下:app
[ 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
能夠看到咱們的監控類是多實例的,它裏面的Dao是單實例的,這樣以來咱們就能夠在spring中使用多線程處理咱們的任務了。ide
如何啓動咱們的多線程任務類,能夠專門定義一個組件類啓動也能夠在啓動Spring的main方法中啓動,下面看下,如何定義組件啓動:
@Component public class StartTask { final static Logger logger= LoggerFactory.getLogger(StartTask.class); //定義在構造方法完畢後,執行這個初始化方法 @PostConstruct public void init(){ final List<Monitor> list = ParseRuleUtils.parseRules(); logger.info("監控任務的總Task數:{}",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("第{}個監控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 配置日誌所生成的目錄以及生成文件名的規則,默認是相對路徑 --> <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>
有什麼問題能夠掃碼關注微信公衆號:我是攻城師(woshigcs),在後臺留言諮詢。 技術債不能欠,健康債更不能欠, 求道之路,與君同行。