java rabbitmq与执行器线程,创建的线程保持运行如何确保线程被终止?

gwbalxhn  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(344)

我用的是rabbitmq接收器。它同时获得多个请求,所以我创建线程来同时处理多个请求。
问题是我创建了newsinglethreadexecutor或newfixedthreadpool,它们仍在运行executor.shutdown();或executor.shutdownnow();不会关闭下面的线程是示例

public void receiver(String message) {

         ExecutorService executor = Executors.newFixedThreadPool(10);
                :
            executor.execute(c);
                :
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.NANOSECONDS);
                executor.shutdownNow();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } 
        }

下面是我的rabbitmq配置

@Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
                                             MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(receiver recv) {
        return new MessageListenerAdapter(recv, "receiver");
    }

线程保持在like thread[pool-1-thread-“number”]
线程是根据我在接收器中收到的请求数量创建的,并且从不关闭。
如何避免这种情况,还是最好完全取消多线程的概念??
提前谢谢

bgibtngc

bgibtngc1#

您首先不应该在侦听器中使用executor,否则您将面临消息丢失的风险。
增加容器 concurrentConsumers 框架将为您管理并发性。

相关问题