티스토리 뷰

Test & ProtoTyping

Activemq 간단 예제

까오기 2020. 4. 3. 12:18

회사에서 activemq를 도입해보고자 환경을 구축하고 테스트를 하는데 mq와 연결도 잘 안되고 이상한 에러가 발생합니다.  이럴때 activemq 프로젝트를 만들어서 연결 및 produce, reciever 를 테스트 하면 원인을 찾기가 수월합니다. 

 

예제는 spring.io에 있는 내용을 그대로 따라했습니다. 

 

출처 https://spring.io/guides/gs/messaging-jms/

What you'll need

  • 대략 15분 정도 소요
  • eclipse 
  • jdk 1.8 or later
  • Gradle

Work flow

1. 프로젝트생성

2. build.gradle 수정 

3. Source Coding 

4. Test 

 

1. 기본 Spring boot 프로젝트를 생성합니다.  

2. build.gradle 수정

plugins {
	id 'org.springframework.boot' version '2.2.6.RELEASE'
	id 'io.spring.dependency-management' version '1.0.9.RELEASE'
	id 'java'
	id 'war'
}

group = 'eblo.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenCentral()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-activemq")
    compile("org.apache.activemq:activemq-broker")
    compile("com.fasterxml.jackson.core:jackson-databind")
    testImplementation('org.springframework.boot:spring-boot-starter-test')
}

test {
	useJUnitPlatform()
}

3. Source Coding 

ActiveMQConfiguration.java

@Configuration
public class ActiveMQConfiguration {

    @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
      //factory.setPubSubDomain(true); // pubsub 설정시 
      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;
    }

}

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());
    }

  }

EmailProducer.java

@Service
public class EmailProducer {

    @Autowired
    private JmsTemplate jmsTemplate;
    
    public void sendMsg(String email, String msg) {
        // jmsTemplate.setPubSubDomain(true); // pubsub 설정시 ... 
        jmsTemplate.convertAndSend("mailbox", new Email(email, msg));
        System.out.println("email : "+email);
        System.out.println("message : "+msg);
        System.out.println("Sending an email message.");
    }
}

Receiver.java

@Component
public class Receiver {

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

}

application.properties

spring.activemq.broker-url=ssl://localhost:61617
spring.activemq.user=userid
spring.activemq.password=password

코드는 딱히 설명할 내용이 없습니다. 

application.properties에 연결 정보 넣으시고 jmsTemplate으로 전송하면 끝입니다. 

 

4. Test

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailProducerTest {

    @Autowired
    private EmailProducer emailProducer;
    
    @Test
    public void testSendMsg() {
        emailProducer.sendMsg("info@example.com", "Hello");
    }

}

console.log 확인 

email : info@example.com
message : Hello
Sending an email message.
Received <Email{to=info@example.com, body=Hello}>

 

Git : https://github.com/kkaok/examples/tree/master/activeMQExample 

'Test & ProtoTyping' 카테고리의 다른 글

Rabbitmq Topic 간단 예제  (0) 2020.04.06
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함