블로그 이미지
평범하게 살고 싶은 월급쟁이 기술적인 토론 환영합니다.같이 이야기 하고 싶으시면 부담 말고 연락주세요:이메일-bwcho75골뱅이지메일 닷컴. 조대협


Archive»


 

'클라우드 컴퓨팅 & NoSQL/RabbitMq'에 해당되는 글 6

  1. 2014.01.02 RabbitMQ 기본 기동 (1)
  2. 2013.09.03 RabbitMQ 공부 노트
  3. 2013.08.27 RabbitMQ + Spring
  4. 2013.08.27 RabbitMQ multi threaded read message consumer
  5. 2013.08.27 RabbitMQ - Receive Message
  6. 2013.08.27 RabbitMQ - Send Message
 

RabbitMQ 기본 기동

클라우드 컴퓨팅 & NoSQL/RabbitMq | 2014.01.02 01:32 | Posted by 조대협

1. 설치

- Erlang 설치

- Rabbit MQ 다운로드 후 설치


2. 기본 명령

  • 서버 기동 : sbin/rabbitmq-server start. 윈도우즈에서는 services.msc에서 서비스로 시작
  • 상태 체크 : sbin/rabbitmqctl status
  • 서버 중지 : sbin/rabbitmqctl stop
3. Web Admin 모듈
  • web admin 모듈 enable - "rabbitmq-plugins enable rabbitmq_management" (이다음 서비스를 restart해야 함)
  • http://localhost:15672/ 접속후 guest/guest로 로그인




저작자 표시
신고

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

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

RabbitMQ 공부 노트

클라우드 컴퓨팅 & NoSQL/RabbitMq | 2013.09.03 21:45 | Posted by 조대협

http://www.rabbitmq.com/tutorials/amqp-concepts.html

 

Rabbit MQ 기본 컨셉

 

AMQP (Advanced Message Queuing Protocol)

Broker : 메세지 Queue 시스템을 broker라고 하낟.

Queue

 

Queue의 주요 속성

Ÿ   name

Ÿ   durable 속성 : 메세지를 디스크에 저장. memory에 저장하는 것은 transient라고 한다.

Ÿ   auto-delete : 모든 consumer unsubscribe하면, 해당 queue는 자동으로 없어진다.

* Queue를 만드는 것을 declare라고 하며, 애플리케이션 코드에서도 쉽게 만들 수 있다. 만약 해당 큐가 이미 존재하고 있다면, 다시 queue를 만들지 않고, queue가 없을 경우에만 만든다. (기존의 JMS 기반의 queuing 시스템과 접근 방법이 좀 틀린 듯. 기존 JMS 시스템은 큐 시스템 admin console등에서 queue를 선언했어야 하지만, rabbit mq는 코드를 통해서 queue를 생성 하는 것이 가능하기 때문에, 손쉽게 배포가 가능하다.)

 

Exchange

 

Exchange 타입

 

Ÿ   Default Exchange

Ÿ   Direct Exchange : Queue Routing Key Binding이 되어 있고, Exchange Routing Key가 들어오면, Exchange Binding되어 있는 Queue중에서,   Key Mapping되어 있는 Queue로 메세지를 라우팅 한다.

Ÿ   Fan out Exchange : Routing Key에 상관 없이 Exchange Binding되어 있는 모든 Queue에 메세지를 라우팅 한다. (1:N 관계로, 모든 Queue에 메세지를 복제해서 라우팅 한다.)

Ÿ   Topic Exchange : Exchange mapping 되어 있는 Queue중에서 Routing key가 패턴에 맞는 Queue로 모두 메세지를 라우팅 한다.

Ÿ   Headers Exchange

 

Binding : Exchange Queue를 연결하는 것을 binding이라고 하며, Binding routing key Exchange type attributeoptional로 동반한다. (routing key는 일종의 filter key 처럼 동작 한다.)

Connection : 물리적인 TCP Connection, 보안이 필요할 경우 TLS(SSL) Connection을 사용할 수 있음.

Channel : 하나의 물리적인 connection 내에 생성되는 가상 논리적인 connection. Consumer process thread는 각자 이 channel을 통해서 queue에 연결 될 수 있다.

Virtual Host : 웹서버의 virtual host concept과 같이, 하나의 물리적인 서버에 여러 개의 가상 서버를 만들 수 있다.

Message Attributes and Payload

 

메세지 구조 : Header, Properties, byte[] data

 

트렌젝션 관리 : rabbit mq XA 기반의 분산 트렌젝션은 지원하지 않음. local 단위에서 ack 받으면 성공 처리함.

 

Clustering HA 구성

 

저작자 표시
신고

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

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

RabbitMQ + Spring

클라우드 컴퓨팅 & NoSQL/RabbitMq | 2013.08.27 22:51 | Posted by 조대협

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

 

  <groupId>com.terry</groupId>

  <artifactId>rabbitmq</artifactId>

  <version>1.0-SNAPSHOT</version>

  <packaging>jar</packaging>

 

  <name>rabbitmq</name>

  <url>http://maven.apache.org</url>

  <repositories>

         <repository>

             <id>spring-release</id>

             <name>Spring Maven Release Repository</name>

             <url>http://repo.springsource.org/libs-release</url>

         </repository>

  </repositories>

 

  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>

 

  <dependencies>

         <dependency>

           <groupId>com.rabbitmq</groupId>

           <artifactId>amqp-client</artifactId>

           <version>3.1.4</version>

         </dependency>

         <!--  spring framework -->

    <dependency>

          <groupId>org.springframework</groupId>

          <artifactId>spring-core</artifactId>

          <version>3.2.2.RELEASE</version>

    </dependency>

    <dependency>

          <groupId>org.springframework</groupId>

          <artifactId>spring-context</artifactId>

          <version>3.2.2.RELEASE</version>

    </dependency>

    <dependency>

          <groupId>org.springframework</groupId>

          <artifactId>spring-beans</artifactId>

          <version>3.2.2.RELEASE</version>

    </dependency>

         <!-- spring rabbit mq -->

                  <dependency>

                  <groupId>org.springframework.amqp</groupId>

                  <artifactId>spring-amqp</artifactId>

                  <version>1.2.0.RELEASE</version>

                  <exclusions>

                           <exclusion>

                                   <groupId>com.sun.jmx</groupId>

                                   <artifactId>jmxri</artifactId>

                           </exclusion>

                  </exclusions>

         </dependency>

         <dependency>

                  <groupId>org.springframework.amqp</groupId>

                  <artifactId>spring-rabbit</artifactId>

                  <version>1.2.0.RELEASE</version>

         </dependency>

         <dependency>

                  <groupId>org.springframework.amqp</groupId>

                  <artifactId>spring-erlang</artifactId>

                  <version>1.2.0.RELEASE</version>

         </dependency>

 

        

         <!--  JUnit 4 -->

         <dependency>

                  <groupId>junit</groupId>

                  <artifactId>junit</artifactId>

                  <version>4.10</version>

         </dependency>

                 

         <!--  logging framework -->

         <dependency>

           <groupId>org.slf4j</groupId>

           <artifactId>slf4j-api</artifactId>

           <version>1.7.5</version>

          </dependency>

          <dependency>

           <groupId>ch.qos.logback</groupId>

           <artifactId>logback-classic</artifactId>

           <version>1.0.13</version>

          </dependency>

          <dependency>

           <groupId>ch.qos.logback</groupId>

           <artifactId>logback-core</artifactId>

           <version>1.0.13</version>

          </dependency>

        

  </dependencies>

</project> 


applicationContext.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:rabbit="http://www.springframework.org/schema/rabbit"

    xsi:schemaLocation="http://www.springframework.org/schema/rabbit

http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 

    <!-- A reference to the org.springframework.amqp.rabbit.connection.ConnectionFactory -->

    <rabbit:connection-factory id="connectionFactory"/>

 

    <!-- Creates a org.springframework.amqp.rabbit.core.RabbitTemplate for access to the broker -->

    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory"/>

 

    <!-- Creates a org.springframework.amqp.rabbit.core.RabbitAdmin  to manage exchanges, queues and bindings -->

    <rabbit:admin connection-factory="connectionFactory"/>

 

    <!-- Creates a queue for consumers to retrieve messages -->

    <rabbit:queue name="simplequeue"/>

</beans>


Producer.java

 

package com.terry.rabbitmq.springframework;

 

import org.springframework.amqp.core.AmqpTemplate;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Producer {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        AmqpTemplate amqpTemplate = context.getBean(AmqpTemplate.class);

        amqpTemplate.convertAndSend("simplequeue", "Hello World");

    }

}


Consumer.java

package com.terry.rabbitmq.springframework;

 

import org.springframework.amqp.core.AmqpTemplate;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.support.GenericXmlApplicationContext;

 

public class Consumer {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        AmqpTemplate amqpTemplate = context.getBean(AmqpTemplate.class);

        System.out.println(amqpTemplate.receive("simplequeue"));

        //System.exit(1);

    }

}

 

저작자 표시
신고

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

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



package com.terry.rabbitmq.queue.threadpool;

 

import java.io.IOException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.rabbitmq.client.AMQP;

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.ConnectionFactory;

import com.rabbitmq.client.DefaultConsumer;

import com.rabbitmq.client.Envelope;

import com.rabbitmq.client.QueueingConsumer;

 

public class QueueListener {

 

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

 

        public void invoke(String uri, String queue, int maxthread ) throws Exception{

              

               log.info("QueueListener has been started");

               ConnectionFactory factory = new ConnectionFactory();

               factory.setUri(uri);

              

               ExecutorService es = Executors.newFixedThreadPool(maxthread);

               Connection conn = factory.newConnection(es);

              

    // Thread 당 다른 Channel 을 사용하기 위해서 Thread수 만큼 별도의 채널을 생성하낟.

               for(int i=0;i<maxthread;i++){

                       Channel channel = conn.createChannel();     

                       channel.basicQos(1);

                       channel.basicConsume(queue,false,new MyQueueConsumer(channel));

               }

               log.info("Invoke "+maxthread+" thread and wait for listening");

 

 

              

        } //invoke

       

        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";

       

        public static void main(String args[]) throws Exception{

               QueueListener ql = new QueueListener();

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

               ql.invoke(uri, "simplequeue", 5);

        }

}


package com.terry.rabbitmq.queue.threadpool;

 

import java.io.IOException;

import java.util.UUID;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.rabbitmq.client.AMQP;

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.DefaultConsumer;

import com.rabbitmq.client.Envelope;

 

public class MyQueueConsumer extends DefaultConsumer {

       

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

        Channel channel;

        public MyQueueConsumer(Channel channel) {

               super(channel);

               // TODO Auto-generated constructor stub

               this.channel = channel;

        }

 

        @Override

        public void handleDelivery(String consumeTag,

                                   Envelope envelope,

                                   AMQP.BasicProperties properties,

                                                        byte[] body)

               throws IOException

        {

               String routingKey = envelope.getRoutingKey();

               String contentType = properties.getContentType();

               long deliveryTag = envelope.getDeliveryTag();

              

               // message handling logic here

               String msg = new String(body);

               UUID uuid = UUID.randomUUID();

               log.debug(uuid+" S Channel :"+channel+" Thread:"+Thread.currentThread()+" msg:"+msg);

              

               // multiple - false if we are acknowledging multiple messages with the same delivery tag

               this.channel.basicAck(deliveryTag, false);

        }

}

 

 


저작자 표시
신고

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

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

RabbitMQ - Receive Message

클라우드 컴퓨팅 & NoSQL/RabbitMq | 2013.08.27 22:23 | Posted by 조대협

※ 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  (0) 2013.08.27
RabbitMQ - Receive Message  (0) 2013.08.27
RabbitMQ - Send Message  (0) 2013.08.27

RabbitMQ - Send Message

클라우드 컴퓨팅 & NoSQL/RabbitMq | 2013.08.27 22:21 | Posted by 조대협

※ 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  (0) 2013.08.27
RabbitMQ - Receive Message  (0) 2013.08.27
RabbitMQ - Send Message  (0) 2013.08.27