ActiveMQ - Large number of queues(HowTo)ActiveMQ - Large number of queues(HowTo)

Posted at 2010. 9. 9. 22:30 | Posted in OpenSource
Large number of queues(HowTo)
http://activemq.2283324.n4.nabble.com/Large-number-of-queues-HowTo-td2364929.html#a2364929
How do I configure 10s of 1000s of Queues in a single broker ?

able to create more than 20k queues using ~30 threads in a test environment with a 512MB heap. (by Jose Luna-2)

<Reduce Threads>
많은 수의 queue를 만들면 다음과 같은 에러를 만나게 된다.
"unable to create new native thread"
이것은 QueueThread가 queue당 하나가 생성되기 때문이다.
http://activemq.apache.org/per-destination-policies.html 에서 queue properties를 설정할 수 있는데,
optimizedDispatch=true(기본값은 false)로 설정하면 된다.
이 옵션은 다음과 같이 설명하고 있다. "don't use a separate thread for dispatching from a Queue"

그러나, 실제로는 queue별로 thread가 생성된다. 이는 optimizedDispatch 는 TaskRunner를 사용하는 thread를 생성하기 때문이다.
thread pool을 사용하기 위해서는 org.apache.activemq.UseDedicatedTaskRunner 를 false로 설정해 줘야 한다.
http://activemq.apache.org/javalangoutofmemory.html - Number of Threads 항목참조

Number of Threads
By default, ActiveMQ uses a dedicated thread per destination. If there are large numbers of Destinations there will be a large number of threads and their associated memory resource usage. ActiveMQ can be configured to use a thread pool through the use of the system property: -Dorg.apache.activemq.UseDedicatedTaskRunner=false. This is currently specified in the activemq start script via ACTIVEMQ_OPTS. Using a thread pool can restrict the number of threads required by ActiveMQ and hence reduce memory usage.

<policyEntries> 
    <policyEntry queue=">" memoryLimit="15mb" optimizedDispatch='true'/> 
</policyEntries>

set the ACTIVEMQ_OPTS to disable dedicated task runners in the start up script, INSTALL_DIR/bin/activemq -e.g.
   ACTIVEMQ_OPTS="-Xmx512M -Dorg.apache.activemq.UseDedicatedTaskRunner=false"  
or you can set ACTIVEMQ_OPTS in /etc/activemq.conf.

<Reduce number of file descriptors>
AMQ Message Store를 사용하기 보다 KahaDB를 사용하기를 권장함(in version 5.3 higher)
※ AMQ Message Store는 queue당 file descriptor 하나를 사용함.

<Reducing Memory Consumption>
Reduce the memory used per thread - http://activemq.apache.org/javalangoutofmemory.html



//

zookeeper 메모zookeeper 메모

Posted at 2010. 8. 10. 01:44 | Posted in OpenSource
목적/사용예
- distributed lock service
- maintaining configuration information
- naming
- distributed synchronization
- group services

//

관심있는 Open Source들관심있는 Open Source들

Posted at 2010. 3. 29. 21:14 | Posted in OpenSource


Distributed Messaging Service (JMS)
ActiveMQ - http://activemq.apache.org/

Application Server Framework
MINA - http://mina.apache.org/
Netty - http://www.jboss.org/netty
Thrift - http://incubator.apache.org/thrift/

Distributed System
Hadoop - http://hadoop.apache.org/, http://developer.yahoo.com/hadoop/
Zookeeper - http://hadoop.apache.org/zookeeper/

Web Server
Jetty - http://jetty.codehaus.org/jetty/
Tomcat - http://tomcat.apache.org/

Email Server
James - http://james.apache.org/




//

ActiveMQ-cppActiveMQ-cpp

Posted at 2010. 3. 14. 15:36 | Posted in OpenSource
http://activemq.apache.org/cms/
ActiveMQ C++ 클라이언트 라이브러리.
JMS와 유사한 형태로 Producer와 Consumer를 작성할 수 있다.

설치
1. apr (Apach Portable Runtime) 설치
   먼저 apr 이 설치되어 있어야 한다.
   http://apr.apache.org/
   로 가서 다운 받아 설치(상세는 apr 페이지 참조).

2. ActiveMQ-cpp를 다운 받아 설치한다.
   http://activemq.apache.org/cms/activemq-cpp-310-release.html
   설치 방법은 다운 받은 소스에 포함된 README.txt 참조.

샘플 실행해 보기
ActiveMQ-cpp 라이브러리들이 필요하므로 설치 시에 prefix를 적절히 주어 원하는 환경에 설치되도록 해두면 좋다.
(prefix 기본값은 /usr/local 이므로 여기에 설치해도 무방)
activemq-cpp-src> ./configure --prefix=/my/lib/activemq
activemq-cpp-src> make
activemq-cpp-src> make install

ActiveMQ-cpp에 포함된 기본 예제 src/examples/producers/SimpleProducer.cpp 를 빌드해 보자.
소스를 내 작업 디렉토리에 복사하고 다음과 같이 Makefile를 작성한다.
AMQ_HOME = /my/lib/activemq

AMQ_INC_DIR = $(AMQ_HOME)/include
AMQ_LIB_DIR = $(AMQ_HOME)/lib
#AMQ_INCS = `$(AMQ_HOME)/bin/activemqcpp-config --includes`
AMQ_INCS = -I${AMQ_INC_DIR}/activemq-cpp-3.1.0
#AMQ_LIBS = `$(AMQ_HOME)/bin/activemqcpp-config --libs`
AMQ_LIBS = -L${AMQ_LIB_DIR} -lactivemq-cpp
AMQ_LIBS += -lpthread -ldl -luuid

APR_CPPFLAGS =  -DLINUX=2 -D_REENTRANT -D_GNU_SOURCE -D_LARGEFILE64_SOURCE

CFLAGS = -g -Wall $(APR_CPPFLAGS)
INCLUDES = $(AMQ_INCS)
LIBS = $(AMQ_LIBS)

TARGET=producer

all:
    g++ $(CFLAGS) -o $(TARGET) SimpleProducer.cpp $(INCLUDES) $(LIBS)
clean:
    rm -f $(TARGET)
※ SimpleProducer.cpp에서 APR_CPPFLAGS는 필요없으나 멀티쓰레드를 사용하거나 확장된 기능을 사용할 것을 고려해 남겨두었다.

make를 하면 실행파일(producer)이 생성된다.
하지만, 실행하면 다음과 같은 에러가 발생한다.
$ ./producer
./producer: error while loading shared libraries: libactivemq-cpp.so.11: cannot open shared object file: No such file or directory
ActiveMQ-cpp 설치 시 prefix를 지정하지 않았다면 /usr/local/lib에 설치되므로 문제없이 실행되었을 것이다.
하지만 위와 같이 다른 path에 ActiveMQ-cpp를 설치했다면 LD_LIBRARY_PATH에 추가해주면 된다.
bash)
    export LD_LIBRARY_PATH=/my/lib/activemq:$LD_LIBRARY_PATH
csh)
    setenv LD_LIBRARY_PATH /my/lib/activemq:$LD_LIBRARY_PATH


실행결과

consumer: Windows-XP (192.168.1.200 java sample)
    - D:\apache-activemq-5.3.0\example>ant consumer -Durl=tcp://192.168.1.100:61616 -Dsubject=TEST.FOO
produser: Linux (192.168.1.100 c++ sample: 위 SimpleProducer.cpp) 예제가 localhost activemq에 메시지를 보냄.
activemq server: Linux(192.168.1.100)

Windows에서 실행시킨 consumer(java 버전)가 잘 동작하고 데이터도 잘 꺼내왔다!

환경설정
http://activemq.apache.org/cms/configuring.html

잘 응용해보자.
//

ActiveMQ clusteringActiveMQ clustering

Posted at 2010. 3. 2. 21:19 | Posted in OpenSource

We support reliable high performance load balancing of messages on a queue across consumers.
consumer가 죽은 경우, unacknowledged 메시지는 다른 consumer에게로 재전송된다.
빠른 consumer는 되는 대로 가져가고 느린 consumer는 느린 대로 가져간다.

Broker clusters
JMS 컨텍스트에서 가장 기본적인 클러스터링 모델은 JMS broker 집합에 JMS client가 접속하면 그중 하나에 연결되며, broker가 down된 경우 자동으로 다른 broker에 연결된다는 것이다.
activemq는 JMS client에서 failover:// 프로토콜을 사용함으로서 이를 실현한다.
Failover Transport Reference 페이지에서 상세를 볼 수 있다.

Discovery of brokers
클라이언트가 자동으로 감지하여 broker에 연결할 수 있도록 auto-discovery of brokers using static discovery or dynamic discovery 를 지원한다.

Networks of brokers
client/server 또는 hub/spoke 스타일의 topology를 가지고, 많은 클라이언트와 많은 broker들을 가진다고 했을 때, producer만 동작하고 consumer가 없을 경우 메시지는 계속 쌓이기만 할 것이다. 이를 피하기 위해 producer와 연결된 broker로부터 consumer와 연결된 broker로 메시지를 옮기는 store and forward 방식의 broker의 network(Networks of Brokers)를 제공한다. 이는 broker의 네트워크를 만드는 분산 queue와 topic(distributed queues and topics)을 제공한다.
Networks of brokers에서 클라이언트는 어떤 broker라도 연결할 수 있으며 클러스터로 묶여 있으므로 failover도 된다.
또한, Networks of brokers는 필요한 만큼의 broker를 추가할 수도 있어 거대한 수의 클라이언트 네트워크로 확장할 수도 있다.
broker가 방화벽을 통과하여 네트워크 사이를 연결할 수도 있다.
그러나, broker 링으로 구성된 네트워크에서 하나의 broker의 고장은 전체 망을 고장나게 할 수도 있다.

Master Slave
기본적으로 모든 메시지는 master/slave cluster사이에서 복제된다(replicated). 따라서 master가 고장인 경우 잃어버리는 메시지 없이 자동으로 slave로 failover 된다.
master/slave cluster는 논리적으로 하나의 메시지 broker로 동작한다.
master - slaves(stand-by) 구조.


The Failover Transport(http://activemq.apache.org/failover-transport-reference.html)

configuration syntax
failover:(uri1,...,uriN)?transportOptions
or
failover:uri1,...,uriN

기본적으로 uri는 리스트에서 랜덤하게 선택된다.
만약, 첫번째를 master로 쓰고 나머지는 slave(backup)로 사용하려면 randomize 옵션을 끈다.
failover:(tcp://primary:61616,tcp://secondary:61616)?randomize=false
※ 옵션 상세는 http://activemq.apache.org/failover-transport-reference.html 참조

Notes
If you use failover, and a broker dies at some point, your sends will block by default. Using TransportListener can help with this regard. It is best to set the Listener directly on the ActiveMQConnectionFactory so that it is in place before any request that may require an network hop.

Pure Master Slave(http://activemq.apache.org/pure-master-slave.html)
shared file system이나 shared database 에 의존하지 않고 fully 복제된 토폴로지를 제공한다.

* slave broker는 master의 모든 메시지를 consume한다.
* master broker는 slave에 메시지를 성공적으로 넘긴 후에 client에 응답을 한다. transaction도 마찬가지.
* 클라이언트는 failover transport를 사용하여 ..

//

ActiveMQ 참고 사이트ActiveMQ 참고 사이트

Posted at 2010. 3. 2. 18:16 | Posted in OpenSource
//

ActiveMQ producer flow controlActiveMQ producer flow control

Posted at 2010. 3. 2. 17:57 | Posted in OpenSource

Producer Flow Control (http://activemq.apache.org/producer-flow-control.html)

Producer가 Async Send할 경우 broker가 flow control 한다.
4.x 버전에서는 TCP flow control로 구현되었으며, 여러 producer가 같은 connection을 공유할 때 데드락등의 문제가 있었다.
5.0 버전에서는 producer 개별로 flow control 가능하게 하여 위의 문제를 해결하였다.
Async Send(http://activemq.apache.org/async-sends.html)시 ProducerWindowSize를 설정해야 한다.
The ProducerWindowSize is the maximum number of bytes of data that a producer will transmit to a broker before waiting for acknowledgment messages from the broker that it has accepted the previously sent messages. In other words, this how you configure the producer flow control window that is used for async sends.
--> producer ack 받지 않고도 계속하여 보낼 수 있는 data 크기(byte)

ActiveMQConnectionFactory connctionFactory = ...
connctionFactory.setProducerWindowSize(1024000);

conf 파일에서 flow control 옵션을 켜고 끌 수 있다.
<destinationPolicy>
      <policyMap>
        <policyEntries>

          <policyEntry topic="FOO.>" producerFlowControl="false" memoryLimit="1mb">
            <dispatchPolicy>
              <strictOrderDispatchPolicy/>
            </dispatchPolicy>
            <subscriptionRecoveryPolicy>
              <lastImageSubscriptionRecoveryPolicy/>
            </subscriptionRecoveryPolicy>
          </policyEntry>

        </policyEntries>
      </policyMap>
</destinationPolicy>

flow control의 결과로 느린 consumer로 인해 데이터가 넘치는 것을 방지한다.

Disable Flow Control
모든 가용한 디스크를 사용할 때까지 메시지를 pending하고 dispatching을 계속 하도록 한다.
Message Cursors(http://activemq.apache.org/message-cursors.html) 가 이를 가능하게 한다.

Message Cursors(http://activemq.apache.org/message-cursors.html)
5.0 이전 버전은 dispatch되야 하는 모든 메시지의 참조를 메모리에 보관했다. 이로 인해 pending될 수 있는 메시지 수에 제한이 가해지게 되었다.
일반적인 접근방식은 storage에 메시지를 저장하고 consumer의 요청이 오면 커서를 사용하여 다음 dispatching point를 얻는다.
5.0버전은 hybrid 접근방식을 취해 consumer가 연결된 경우 direct로 전달하고 consumer속도가 떨어지게 되면 cursor를 사용하는 모드로 변경한다.



If a Consumer becomes active after messages are pending from the store for it, or it's slower than the producer, then messages are paged in to the dispatch queue from a pending cursor:


The default message cursor type in ActiveMQ 5.0 is Store based. 여기에 2가지 추가 커서 타입이 있다:
VM Cursor 와 File based Cursor

VM Cursor는 4.X 버전이 동작하는 방식이다. 메시지의 참조를 모두 메모리에 저장한다.
매우 빠르지만, 속도가 느린 consumer인 경우 위험하다.


FileCursor는 VM Corsor에서 파생되었다.broker의 메모리가 한계에 다다르면 그 정보를 파일에 쓴다.


non-persistent 메시지의 경우 cursor로 바로 패스된다.

topic
<destinationPolicy>
      <policyMap>
        <policyEntries>
          <policyEntry topic="org.apache.>" producerFlowControl="false" memoryLimit="1mb">
            <dispatchPolicy>
              <strictOrderDispatchPolicy />
            </dispatchPolicy>
            <deadLetterStrategy>
              <individualDeadLetterStrategy  topicPrefix="Test.DLQ." />
            </deadLetterStrategy>
            <pendingSubscriberPolicy>
            <vmCursor />
            </pendingSubscriberPolicy>
            <pendingDurableSubscriberPolicy>
                <vmDurableCursor/>
            </pendingDurableSubscriberPolicy>
          </policyEntry>
        </policyEntries>
      </policyMap>
</destinationPolicy>
Valid Subscriber types are vmCursor and fileCursor. The default is the store based cursor.
Valid Durable Subscriber cursor types are vmDurableCursor and fileDurableSubscriberCursor. The default is the store based cursor

queue
<destinationPolicy>
      <policyMap>
        <policyEntries>
          <policyEntry queue="org.apache.>">
            <dispatchPolicy>
              <strictOrderDispatchPolicy />
            </dispatchPolicy>
            <deadLetterStrategy>
              <individualDeadLetterStrategy queuePrefix="Test.DLQ."/>
            </deadLetterStrategy>
            <pendingQueuePolicy>
            <vmQueueCursor />
            </pendingQueuePolicy>
          </policyEntry>
        </policyEntries>
      </policyMap>
</destinationPolicy>
Valid Queue cursor types are vmQueueCursor and fileQueueCursor. The default is the store based cursor

System usage
You can also slowdown producers using the <systemUsage> configuration tag.
<systemUsage>
  <systemUsage>
    <memoryUsage>
      <memoryUsage limit="20 mb"/>
    </memoryUsage>
    <storeUsage>
      <storeUsage limit="1 gb" name="foo"/>
    </storeUsage>
    <tempUsage>
      <tempUsage limit="100 mb"/>
    </tempUsage>
  </systemUsage>
</systemUsage>

메시지가 가득찬 경우 default 설정은 send() call을 block시킨다.
이런경우 sendFailIfNoSpace 가 true로 설정하여 send() 이 실패하도록 할 수 있다.
<systemUsage>
<systemUsage sendFailIfNoSpace="true">
   <memoryUsage>
     <memoryUsage limit="20 mb"/>
   </memoryUsage>
</systemUsage>
</systemUsage>

5.3.1 버전에서는 sendFailIfNoSpaceAfterTimeout 속성을 이용하여 일정시간 이후에 send() fail을 발생시킬 수 있다.
<systemUsage>
<systemUsage sendFailIfNoSpaceAfterTimeout="3000">
   <memoryUsage>
     <memoryUsage limit="20 mb"/>
   </memoryUsage>
</systemUsage>
</systemUsage>
millisecond 이다.
//