Spring Boot - 非Web应用的长时间运行应用程序

4
我有一个简单的Spring-Boot应用程序,只使用AMQP依赖项(仅为'org.springframework.boot:spring-boot-starter-amqp' - 例如没有Web依赖项,因此不包括在JAR中的应用程序服务器)。
我只想让应用程序运行并监听队列,在每次接收到消息时将一些信息记录到数据库中。然而,由于没有应用程序服务器,一旦它启动就会立即关闭(因为没有任何操作)。是否有最佳方法使此应用程序在接收消息时保持运行状态?
代码中没有令人惊讶的内容,只有标准应用程序配置,以及一个带有@RabbitListener注释的类。
@SpringBootApplication
class PersistenceSeriveApplication {

    static void main(String[] args) {
        SpringApplication.run PersistenceSeriveApplication, args
    }
}

@Configuration
@EnableRabbit
class QueueConfiguration {

    @Bean public Queue applicationPersistenceQueue( @Value( '${amqp.queues.persistence}' ) String queueName ) {
        new Queue( queueName )
    }
}

我考虑的一个选项是启动一个定时进程 - 只是一个心跳或其他类似的东西,这可能对监控也很有用 - 但是否还有其他更好/标准的方法?


你是否开始启动MessageListenerContainer bean? - guido
@ᴳᵁᴵᴰᴼ 啊,是的,你说得对。那只是我的疏忽 - 在SpringBoot AMQP入门示例中甚至有MessageListenerContainer - 我应该给自己的问题点个踩!如果你想把它作为答案,我会标记为正确的(否则今晚稍后会添加详细答案)。 - rhinds
1个回答

2

您需要确保启动消息监听器容器bean,就像示例中所示:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接