클라우드 컴퓨팅 & NoSQL/RabbitMq

RabbitMQ - Receive Message

Terry Cho 2013. 8. 27. 22:23

※ simplequeue 라는 이름으로 큐를 먼저 만들고 시작할것


package com.terry.rabbitmq.queue;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.ConnectionFactory;

import com.rabbitmq.client.QueueingConsumer;

 

public class MessageReceiver {

       

        Logger log = LoggerFactory.getLogger(MessageReceiver.class);

 

        public String receive(String uri,String queue) throws Exception{

               ConnectionFactory factory = new ConnectionFactory();

               factory.setUri(uri);

              

               log.debug("Connect to :"+uri);

              

               Connection conn = factory.newConnection();

               Channel channel = conn.createChannel();     

               String msg = null;

               try{

                       QueueingConsumer consumer = new QueueingConsumer(channel);

                       channel.basicQos(1);

                       channel.basicConsume(queue,false,consumer);

                       log.debug("Reading msg from (queue:"+queue+")");

                      

                       QueueingConsumer.Delivery delivery = consumer.nextDelivery();

                       msg = new String(delivery.getBody());

                       channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

                       log.debug("Recieve message from (queue:"+queue+"):"+msg);

                      

               }catch(Exception e){

                       e.printStackTrace();

                       throw(e);

               }finally{

                       channel.close();

                       conn.close();

               }

               return msg;

        }

}


단위테스트 코드

package com.terry.rabbitmq.queue.test;

 

import static org.junit.Assert.assertNotNull;

 

import org.junit.Test;

 

import com.terry.rabbitmq.queue.MessageReceiver;

 

 

public class QueueReceiverTest {

        final static String host = "127.0.0.1";

        final static String vhost = "";

        final static int port = 5672;

        final static String user = "rabbitmq";

        final static String password = "rabbitmq";

        final static String queue = "simplequeue";

       

        @Test

        public void MessageReceiverTest() throws Exception{

               MessageReceiver receiver = new MessageReceiver();

               String uri = "amqp://"+user+":"+password+"@"+host+":"+port;//+"/"+vhost;

               String msg = receiver.receive(uri, queue);

               assertNotNull(msg);

        }

       

 

       

}

 

 

'클라우드 컴퓨팅 & NoSQL > RabbitMq' 카테고리의 다른 글

RabbitMQ 기본 기동  (1) 2014.01.02
RabbitMQ 공부 노트  (0) 2013.09.03
RabbitMQ + Spring  (0) 2013.08.27
RabbitMQ multi threaded read message consumer  (1) 2013.08.27
RabbitMQ - Send Message  (0) 2013.08.27