用java内部队列实现推送任务和消费任务的解耦合

直接贴代码,拿过去直接就能用

import java.util.concurrent.LinkedBlockingQueue;

/**
 * 用java内部队列实现推送任务和消费任务的解耦合
 * 队列的大小和线程池的大小可以根据实际情况进行调整
 */
@Service
@Slf4j
public class PushTaskQueueService implements InitializingBean, DisposableBean {


    @Autowired
    private PushTaskDoService pushTaskDoService;

    //队列
    private final LinkedBlockingQueue<MaterialPushTask> queue = new LinkedBlockingQueue<>(10000);

    private boolean toStop = false;
    private Thread writeThread;


    //往队列放数据
    public void addTask(MaterialPushTask task) {
        queue.offer(task);
    }

    public MaterialPushTask takeTask() throws InterruptedException {
        return queue.take();
    }


    @Override
    public void destroy() throws Exception {
        queue.clear();
    }

    //项目启动加载的代码
    @Override
    public void afterPropertiesSet() throws Exception {
        this.writeThread = new Thread(() -> doOperation(), "task-operation-thread");
        this.writeThread.setDaemon(true);
        this.writeThread.start();
        this.toStop = false;
    }


    public void stop() {
        this.toStop = true; //设置停止标志
        this.writeThread.interrupt(); //中断线程
    }

    private void doOperation() {
        while (!toStop) {
            try {
                MaterialPushTask task = queue.take();
                //TODO 这里写具体的操作逻辑
                pushTaskDoService.pushTaskDo(task);
                log.info("素材任务推送执行任务:{}", task.toString());
            } catch (InterruptedException e) {
                //忽略异常
                Thread.currentThread().interrupt();
            }
        }
    }


}

 

posted @ 2024-08-02 17:07  知行IT讲堂  阅读(22)  评论(0)    收藏  举报