Spring Factory创建同步消费者监听队列

时间:2017-06-28 10:47:01

标签: java spring-boot activemq spring-jms

我是Spring Boot的新手并为我的大学项目工作编码,我需要一些帮助。 我想创建一个spring boot应用程序,它启动一个工厂类,创建并启动10个同步客户端。这些客户端必须经常收听队列。以下是我的代码。我不确定,如果我走上正轨并需要一些帮助。我的实施是否正确?如何确保创建10个同步客户端?如何使用标识符来标识哪个消息客户端处理了消息?

Application.java

@SpringBootApplication
public class Application {

    @Bean
    public MesFactory mesFactory(){
        return new MesFactory();
    }

    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
}

public class MesFactory {

    private ExecutorService executorService = 

    Executors.newFixedThreadPool(10);

    @PostConstruct
    public void build(){
        executorService.execute(() -> new MesClient());
    }
}


@Component
@EnableJms
public class MesClient {

    private static final Log log = LogFactory.getLog(MesClient.class);

    @Autowired
    private JmsTemplate jmsTemplate;

    @JmsListener(destination = "incoming-messages-queue")
    public void receive(String message) {
        System.out.println("Received <" + message + ">");
        doPerformMessage(message);
    }

    public void doPerformMessage(String message){
       // parsing happens here
    } 

    @Bean
    ConnectionFactory connectionFactory() {
        return new RMQConnectionFactory();
    }

    @Scheduled(fixedRate = 100000000L)
    public void sendMessage() {

        String message= "Hi World";

        // Coerce a javax.jms.MessageCreator
        MessageCreator messageCreator = (Session session) -> {
            return session.createTextMessage(message);
        };

        // And publish to RabbitMQ using Spring's JmsTemplate
        jmsTemplate.send("incoming-messages-queue", messageCreator);
    }

}

1 个答案:

答案 0 :(得分:2)

设置引导属性...

spring.jms.listener.concurrency=10
spring.jms.listener.max-concurrency=10

侦听器容器将启动10个线程 - 每个线程从同一队列中消耗;他们将调用JMS侦听器方法。

请参阅Spring Boot documentation - Application Properties并向下滚动到JMS部分。