美文网首页
Springboot配置多线程定时任务Schedule

Springboot配置多线程定时任务Schedule

作者: 骑蚂蚁上高速_jun | 来源:发表于2020-11-15 20:34 被阅读0次

一.为什么需要配置多线程定时任务& 多线程定时任务的配置使用场景

springboot中通过注解 @Scheduled 注解的方法都是一个定时执行的任务, 默认都是单线程的,就算是多个定时任务也是在同一个单线程(scheduled-1)中运行, 如果其中某一个定时任务产生了阻塞,那么会导致项目中其他所有的定时任务线程都不执行。后果非常严重,故而需要配置多线程定时任务。

二. 多线程定时任务配置类

package com.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;

@Configuration
@EnableScheduling // 开启定时任务
public class ScheduledConfiguration implements SchedulingConfigurer{

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("scheduled@");// 设置定时任务线程名称的前缀
        int corePoolSize  = 10; // 设置定时任务的核心线程数
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize,executor));
    }
}

三. 多线程定时器的案例

package com.task;

import com.dinstone.beanstalkc.BeanstalkClientFactory;
import com.dinstone.beanstalkc.Configuration;
import com.dinstone.beanstalkc.Job;
import com.dinstone.beanstalkc.JobConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@Lazy(false)
public class CrontabTask {

    @Autowired
    SmtpSendMailer smtpSendMailer; // 线程池对象

    // 定时任务1,用于测试
    @Scheduled(fixedDelay = 3000)
    public void test1() throws IOException {
        Thread thread = Thread.currentThread();
       log.error("test定时任务处理线程 : "+thread.getName());
    }
    // 定时任务2,用于测试
    @Scheduled(fixedDelay = 5000)
    public void test2() throws IOException {
        Thread thread = Thread.currentThread();
        log.error("test1定时任务处理线程 : "+thread.getName());
    }

    // 定时任务3,监听beanstalk
    @Scheduled(fixedDelay = 1)
    public void beanstalk() {
        Thread thread = Thread.currentThread();
        log.error("BeanstalkListenerTask处理线程 : "+thread.getName());
        Configuration config = new Configuration();
        config.setServiceHost("8.129.0.115");
        config.setServicePort(11300);
        BeanstalkClientFactory factory = new BeanstalkClientFactory(config);
        JobConsumer consumer = factory.createJobConsumer("smtp-mail");
        Job job = null;
        while(true){
            try{
                job = consumer.reserveJob(30);
            }catch(Throwable e){
                continue;
            }
            if (Objects.isNull(job)) continue;
            String jobString = new String(job.getData());

            log.error("beanstalk处理任务的线程名称:"+thread.getName() + ";线程id是:"+thread.getId());
            // if(!JSONObject.isValid(jobString)) continue;// 由于客户端是其他语言编写,故要求是json数据格式
            System.out.println(jobString);
            smtpSendMailer.sendMailer();
            consumer.deleteJob(job.getId()); // 删除任务
        }
    }

    @Autowired
    @Qualifier("default")
    RedisTemplate redisTemplate;

    // 定时任务4监听redis list 实现的消息队列
    @Scheduled(fixedDelay = 2)
    public void redisList(){
        System.out.println("redis list 监听消息队列");
        Thread thread = Thread.currentThread();
        Map<String,Object> obj = null;
        while(true){
            try{
                obj  = (Map<String, Object>) redisTemplate.opsForList().rightPop("list",3, TimeUnit.SECONDS);
            }catch(Throwable e){
                // 要求客户端发送的数据必须是 合法的json字符串.
                System.out.println("redis list数据非法");
                continue;
            }
            if(Objects.isNull(obj)) continue;
            System.out.println(obj);
            log.error("redis list执行的线程名称:"+thread.getName());
        }
    }


}

相关文章

网友评论

      本文标题:Springboot配置多线程定时任务Schedule

      本文链接:https://www.haomeiwen.com/subject/lgfobktx.html