Springboot JMS

A production JMS server must be a stand alone server. What we have here is for demonstration purposes.

Add dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

Add configuration class

@Configuration
@EnableJms
public class JmsConfig {

    @Bean
    public JmsListenerContainerFactory<?> jmsFactory(ConnectionFactory connectionFactory,DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }
    
    @Bean // Serialize message content to json using TextMessage
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;
    }
}

Add a Sender

@Slf4j
@Component
public class Sender {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Value("${queue.sender-receiver}")
    private String      queue;

    public void sendMail(Mail mail) {
        try {
            jmsTemplate.convertAndSend(queue, mail);
            log.info("Mail sent to queue, {}, at {}", queue, LocalDateTime.now());
        } catch (Exception e) {
            log.error("Mail not sent");
            log.error("Exception, msg: {}", e.getMessage());
        }

    }

}

Add a Receiver

@Slf4j
@Component
public class Receiver {

    @JmsListener(destination = "${queue.sender-receiver}", containerFactory = "jmsFactory")
    public void receiveMessage(Mail mail) {
        log.info("Received mail {}", LocalDateTime.now());
        try {
            log.info("mail={}", ObjectUtils.toJson(mail));
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

    }

}

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *