2 Star 1 Fork 0

zhrun8899 / learning-notes

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
springboot中的多线程.md 6.52 KB
一键复制 编辑 原始数据 按行查看 历史
zhrun8899 提交于 2019-03-20 10:03 . add some docs

1、程序运行时,自动启动;

这在一般的可执行程序里面,当然可以直接在main函数里执行通过代码启动线程。但在springboot中,我们可以使用@PostConstruct注解的方式,让已经注入bean容器的线程对象自启动

@Component
public class  demoThread extends Thread
{
//注意这里,如果你没有实现把多线程类的实例注入到spring容器中,这里你是无法拿到其他自动装配的对象实例的的,这也是我们第一步的意义所在。
@Autowired
private XxxService xxxService;

@PostConstruct
public void start() {
super.start();
}
public void run() {
// Ok,在这里你就可以实现线程要实现的功能逻辑了,自然也可以直接使用装配好的sevice对象实例。   
}
}

ApplicationConfig.java

import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class ApplicationConfig {
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("thread-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

调用:

 package com.webimation.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import com.webimation.cindy.mail.server.MailServer;
import com.webimation.thread.PushMailThread;
import com.webimation.thread.ReportMailThread;
import com.webimation.thread.RespMailThread;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Order(20)
public class AppInit implements ApplicationRunner {
    /** 项目在spring完成初始化,加载其它自己需要的类 */
    @Autowired
    QueueFactory queueFactory;
    @Autowired
    AppProps appProps;
    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        log.info("1.检查队列......");
        log.info("QueueMailPush容量:{}", queueFactory.getQueueMailPush().remainingCapacity());
        log.info("QueueMailResp容量:{}", queueFactory.getQueueMailResp().remainingCapacity());
        log.info("QueueMailReport容量:{}", queueFactory.getQueueMailReport().remainingCapacity());

        log.info("2.初始化线程......");

        PushMailThread pushMailThread = ApplicationContextProvider.getBean("pushMailThread", PushMailThread.class);
        // pushMailThread.start();
        taskExecutor.execute(pushMailThread);
        log.info("--(1)PushMailThread 启动");
        ReportMailThread reportMailThread = ApplicationContextProvider.getBean("reportMailThread",
                        ReportMailThread.class);

        // reportMailThread.start();
        taskExecutor.execute(reportMailThread);
        log.info("--(2)reportMailThread 启动");
        RespMailThread respMailThread = ApplicationContextProvider.getBean("respMailThread", RespMailThread.class);

        // respMailThread.start();
        taskExecutor.execute(respMailThread);
        log.info("--(3)respMailThread 启动");

        log.info("3.创建socket监听......");
        new MailServer(appProps.getMailPort(), queueFactory);

    }

}

线程定义:

package com.webimation.thread;
import java.util.Date;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.icexxx.util.IceJsonUtil;
import com.webimation.config.AppProps;
import com.webimation.config.QueueFactory;
import com.webimation.entity.PushMail;
import com.webimation.entity.PushMailMsg;
import com.webimation.util.JodaDateUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component("pushMailThread")
@Scope("prototype")
public class PushMailThread implements Runnable {
    @Autowired
    QueueFactory queueFactory;
    @Autowired
    AppProps appConfig;
public PushMailThread() {

}

public void run() {
    while (true) {
        log.info("进入线程,时间间隔{}", appConfig.getSleepTime());
        try {
            HashMap<String, Object> map = (HashMap<String, Object>) queueFactory.getQueueMailPush().take();
            log.info("取到记录,准备处理{}", map);
            PushMail pushMail = new PushMail();
            pushMail.setEmpiId(Integer.parseInt(map.get("empiId").toString()))
                            .setPhoneNo(map.get("phoneNo").toString())
                            .setProductCode(map.get("serviceType").toString())
                            .setPushSeq(map.get("sequnceId").toString())
                            .setTimePush(JodaDateUtil.date2str(new Date(), JodaDateUtil.Pattern.yyyyMMddHHmmss));
            pushMail.insert();
            PushMailMsg pushMailMsg = new PushMailMsg();
            pushMailMsg.setPushId(pushMail.getId());
            /* 整个map转json存诸即可 */
            pushMailMsg.setMsg(IceJsonUtil.format(map));

            pushMailMsg.insert();

            Thread.currentThread().sleep(appConfig.getSleepTime());
        } catch (Exception ex) {
            log.error(ex.getLocalizedMessage());
            try {
                Thread.currentThread().sleep(appConfig.getSleepTime() * 2);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            continue;
        }
    }
}}
1
https://gitee.com/zhrun8899/learning-notes.git
git@gitee.com:zhrun8899/learning-notes.git
zhrun8899
learning-notes
learning-notes
master

搜索帮助