2015년 9월 9일 수요일

20150910 Spring 없이 ActiveMQ 사용해보기!

검색 능력이 미천한데다가, 이해를 잘 못해서 또 남겨 놓게 되었습니다.

대부분의 ActiveMQ를 알려주는? 블로그?들은 Spring에서 사용하기 때문에
Spring과 관련된 포스팅을 해 놨습니다.
저는 실무에서 웹을 다루지 않기 때문에 늦는 느낌이지만,
어쨋든 ActiveMQ 사용법 without Spring을 남겨놔 봅니다.

가장 먼저,
http://activemq.apache.org/ 를 방문해 헤더 아래의
Download ActiveMQ 5.12.0 Today! 를 클릭합니다. (http://activemq.apache.org/download.html)

2. ActiveMQ 5.12.0 Release 를 클릭 합니다.
저는 윈도우 환경이니 apache-activemq-5.12.0-bin.zip를 다운로드 했습니다.

3. 저는 바탕화면에 풀었습니다.

4. 콘솔에서(윈도우키 + R -> cmd) ->풀어진 폴더/bin 으로 이동한 후
activemq start를 입력 후 엔터!

5. http://127.0.0.1:8161/admin 접속 후 아이디와 비밀번호 모두 admin을 입력합니다.

여기까지 기본 작업이 끝났습니다. 
아래는 스프링 없이 큐를 이용해 메시지를 쌓고 꺼내고 를 하는 소스입니다.

ProducerQ.java 를 만들고 main메소드를 생성 후 아래 코드를 붙여 넣습니다.
public class ProducerQ {
public static void main(String[] args) {
ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection conn = null;
Session session = null;
try {
conn = cf.createConnection();
session = conn.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination destination = new ActiveMQQueue("queueName");
MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
message.setText("Hello ActiveMQ world!");
producer.send(message);
} catch (JMSException e) {
} finally {
try {
if(session != null) { session.close(); }
if(conn != null) { conn.close(); }
} catch (JMSException ex) {}
}
 
}
}

1. 커넥션 팩토리 생성. 이때 자동 설정된 ActiveMQ의 포트 61616으로 접속도록 설정 해줍니다.
2. 데스티네이션을 내가 만든 큐 (이름은 queueName)으로 설정합니다.
3. 해당 큐로 프로듀서를 생성합니다. 앞으로 보내는 메시지는 이 프로듀서를 이용해 큐에 쌓게 됩니다.
4. 보낼 메시지를 생성합니다(여기는 TextMessage 이고, 여러 종류의 Message가 가능합니다).
5. 프로듀서에게 메시지를 전달합니다.
6. 그럼 큐에 쌓이게 되고 아까 접속했던 어드민 페이지의 Queues 탭에서 확인 할 수 있습니다.


같은 방법으로 ConsumerQ.java도 마찬가지로 붙여 넣습니다.
public class ConsumerQ{

public static void main(String[] args) {
ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection conn = null;
Session session = null;
try {
conn = cf.createConnection();
session = conn.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination destination = new ActiveMQQueue("queueName");
MessageConsumer consumer = session.createConsumer(destination);
conn.start();
Message message = consumer.receive();
TextMessage textMessage = (TextMessage) message;
System.out.println("From Queue: " + textMessage.getText());
} catch (JMSException e) {
System.out.println(e);
} finally {
try {
if(session != null) { session.close(); }
if(conn != null) { conn.close(); }
} catch (JMSException ex) {}
}
}

}

여기서는 프로듀서 대신 컨슈머를 생성해 큐에 쌓인 메시지를 받고(큐의 이름이 같아야 합니다) 해당 메시지를 출력하므로써 소모합니다.

이제 기본이 되었으니 좀더 심화해서 공부해야겠습니다.


댓글 없음:

댓글 쓰기