簡體   English   中英

具有EJB Timer Service的Java多線程

[英]Java multithreading with EJB Timer Service

我需要每分鍾從數據庫中選擇一批消息(大約20條消息),並且需要同時處理它們。 我正在使用EJB計時器服務(調度程序)每分鍾從數據庫中獲取消息。

基本上,我需要每分鍾選擇20到30條消息,處理這些消息后,我需要發送一些郵件。 處理消息涉及的數據庫操作很少。

您能否建議我如何使用java.concurrent包中的executor服務框架,以及如何每分鍾提交這些消息?

您好,這里是使用Java的ExecutorService,CountDownLatch和CompletableFuture的基本示例。 這個示例只是為了向您指出正確的方向,而絕不是一個完美的示例,它使用了很多Java8的東西(我假設您正在使用Java8)。 另外,我不是在使用EJB Timer東西,而是與ScheduledExecutorService一起使用,但是我想您可以輕松地交換它們。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class BatchMessageProcessingExample {

    private static final int BATCH_SIZE = 20;

    //Having 20 here may not entirely benefit you. Chosing this number depends on a lot of stuff.
    // Its usually better to go with total number of cores you have
    private final ExecutorService pool = Executors.newFixedThreadPool(BATCH_SIZE);

    private final ScheduledExecutorService databasePool = Executors.newScheduledThreadPool(1);

    public void schedule() {
        databasePool.scheduleWithFixedDelay(() -> runBatchProcess(), 0, 1, TimeUnit.MINUTES); //Schedule the database work to execute every minute
    }

    private void runBatchProcess() {
        List<Message> taskFromDbFetch = getMessagesFromDb(); //Get stuff from the db
        CountDownLatch countDownLatch = new CountDownLatch(taskFromDbFetch.size()); //Create a latch having same size as the list

        List<Task> taskList = taskFromDbFetch.stream().map(x -> new Task(countDownLatch, x)).collect(Collectors.toList()); // Create tasks using the messages and the countdown latch

        taskList.forEach(pool::execute); //Submit them all in pool

        CompletableFuture.runAsync(() -> sendEmailAfterCompletion(countDownLatch)); //Send an email out from a separate thread
    }

    private void sendEmailAfterCompletion(CountDownLatch countDownLatch) {
        try {
            countDownLatch.await();//Await on the latch for the batch tasks to complete
            sendEmail();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void sendEmail() {
        System.out.println("Sending out an email.");
    }

    private List<Message> getMessagesFromDb() { //Get your messages from db here
        List<Message> messages = new ArrayList<>();

        for(int i = 0; i < BATCH_SIZE; i++) {
            final int taskNumber = i;
            messages.add(() -> System.out.println("I am a db message number " + taskNumber));
        }

        return messages;
    }

    class Task implements Runnable {

        private final CountDownLatch countDownLatch;

        private final Message message;

        public Task(CountDownLatch countDownLatch, Message message) {
            this.countDownLatch = countDownLatch;
            this.message = message;
        }

        @Override
        public void run() {
            message.process(); //Process the message
            countDownLatch.countDown(); //Countdown the latch
        }
    }

    interface Message {
        void process();
    }

    public static void main(String[] args) {
        new BatchMessageProcessingExample().schedule();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM