JMS 를 이용한 메시징

By | 2021년 7월 17일
Table of Contents

JMS 를 이용한 메시징

목표

activemq 를 이용해, 메시징 시스템을 구성합니다.

프로젝트 생성

신규 프로젝트를 생성합니다.

의존성은 DevTools, Lombok, Spring for Apache ActiveMQ 5 을 선택합니다.

Message Receiver 생성

Email.java 를 생성합니다.

public class Email {

    private String to;
    private String body;

    public Email() {
    }

    public Email(String to, String body) {
        this.to = to;
        this.body = body;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return String.format("Email{to=%s, body=%s}", getTo(), getBody());
    }
}

Receiver.java 를 생성합니다.

@Component
public class Receiver {

    @JmsListener(destination = "mailbox", containerFactory = "myFactory")
    public void receiveMessage(Email email) {
        System.out.println("Received <" + email + ">");
    }
}

메시지 송수신

Application 클래스에서 메시지를 송신하고, 수신되는 내용이 로그에 출력되는 것을 확인할 수 있습니다.

@SpringBootApplication
@EnableJms
public class JmsApplication {

    public static void main(String[] args) {

        // Launch the application
        ConfigurableApplicationContext context = SpringApplication.run(JmsApplication.class, args);

        JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);

        // Send a message with a POJO - the template reuse the message converter
        System.out.println("Sending an email message.");
        jmsTemplate.convertAndSend("mailbox", new Email("info@example.com", "Hello"));
    }

    @Bean
    public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
                                                    DefaultJmsListenerContainerFactoryConfigurer configurer) {

        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        // This provides all boot's default to this factory, including the message converter
        configurer.configure(factory, connectionFactory);
        // You could still override some of Boot's default if necessary.
        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;
    }
}

One thought on “JMS 를 이용한 메시징

  1. Pingback: Spring Boot 시작하기 – 상구리의 기술 블로그

답글 남기기