클라우드 컴퓨팅 & NoSQL/RabbitMq

RabbitMQ - Send Message

Terry Cho 2013. 8. 27. 22:21

※ simplequeue 라는 이름으로 rabbitmq 콘솔에서 먼저 큐를 만들고 시작할것





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;

 

public class MessageSender {

 

 

       

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

 

        public boolean sendMessage(String uri, String queue,String msg) throws Exception{

               ConnectionFactory factory = new ConnectionFactory();

               factory.setUri(uri);

              

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

              

               Connection conn = factory.newConnection();

               Channel channel = conn.createChannel();

               try{

                       byte[] messageBodyBytes = msg.getBytes();

                       log.debug("Send msg (queue:"+queue+") msg:"+msg);

                       channel.basicPublish("", queue, null, messageBodyBytes);

               }catch(Exception e){

                       e.printStackTrace();

                       return false;

               }finally{

                       channel.close();

                       conn.close();

               }

               return true;

        }

 

}



다음은 단위 테스트 코드

package com.terry.rabbitmq.queue.test;

 

import static org.junit.Assert.assertTrue;

 

import org.junit.Test;

 

import com.terry.rabbitmq.queue.MessageSender;

 

 

public class QueueSenderTest {

        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 MessageSenderTest() throws Exception{

               MessageSender sender = new MessageSender();

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

               String msg = "hello world" + System.currentTimeMillis();

              

               for(int i=0;i<1000;i++)

               assertTrue(sender.sendMessage(uri, queue, 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 - Receive Message  (0) 2013.08.27