ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JMS API
    개발노하우/Java 2010. 8. 9. 21:32
    #######################################
    # JMS(Java Message Service) API
    #######################################
    - JMS API는 애플레케이션에서 메시지를 생성하고 전송하고 전송받고 읽는 기능을 구현할 때 사용하는 Java API이다.
    - 메세징은 느슨한 연결(Lazy Connection)되어 있는 분산 처리 시스템의 통신방법이다.
    - 메시징은 보내는 쪽이 직접 메시지를 받는 쪽에 전달하는 것이 아니라 "목적지"라는 특별한 저장소로 전달하는 것이기 때문에받는쪽에 대한 어떠한 정보도 알 필요가 없다. 마찬가지로 받는 쪽에서도 보내는 쪽의 정보를 알 필요 없이 목적지로부터 메시지를전달받으면 된다. 따라서 보내는 쪽과 받는 쪽 모두 메시지가 어떤 형태이고 목적지가 어딘지만 알면 되는 것이다.
    - JMS API는 느슨하게 연결된 통신 방법뿐 아니라 다음과 같은 특징도 가지고 있다.
       - 비동기식 : JMS제공자는 자신에게 전달된 메시지를 메시지를 전달받은 클라이언트에게 비동기식으로 전달할 수 있다.
       - 신뢰성 : JMS API는 오직 한번만 전달된다. 목적지에 전달된 메시지는 전달받으려는 클라이언트에게 메시지가 전달된 후에는 다시 전달되지 않는다. 이는 신뢰성이 낮은 수준의 메시지를 잃어버리거나 중복된 메시지가 잔달되는 애플리케이션에서 많은 도움이 될 수 있다.
    - RPC(Remote Procedure Call)보다 JMS가 사용되는게 바람직한 경우
       - 다른 컴포넌트의 인터페이스 정보에 의존하지 않고 컴포넌트가 쉽게 변경되는 서비스를 원할 때
       - 동시에 모든 애플리케이션이 작동하고 있는 상황에서 특정 애플리케이션이 작동하기를 원할때
       - 애플리케이션 비즈니스 모델을 사용하는 컴포넌트가 다른 곳으로 정보를 전달하고, 바로 응답을 받지 않은 상태에서도 계속 작동하는것을 원할때
     
    ########################################
    # JMS API 기본 개념
    ########################################
    1. JMS API 구조(JMS API Architecture)
       - JMS 제공자(JMS Provider) : JMS 인터페이스를 구현하고 관기 기능과 제어 기능을 가지고 있는 메시징 시스템을 말한다. J2EE1.3 플랫품 이후부터는 애플리케이션 서버에 JMS 제공자가 포함되고 있다.
       - JMS 클라이언트(JMS Client) : 메시지를 생산하고 소비하는 자바 언어로 작성된 프로그램이나 컴포넌트를 말한다. 모든 J2EE 애플리케이션 컴포넌트는 JMS 클라이언트로 사용될 수 있다.
       - 메시지(Message) : JMS클라이언트 간에 통신 정보를 주고받을 수 있는 객체를 말한다.
       - 관리객체(Administered Object) : 클라이언트가 사용하기 위해 미리 설정된 JMS 객체로서 애플리케이션 관리자가 생성한다. JMS 관리 객체는 목적지와 커넥션 팩토리 두 가지가 있다.
                                              
    2. 메시징 도메인(Messaging Domain)
       - 메시징 도메인인란 JMS API를 이용하여 개발한 애플리케이션으로 JMS API 이전에는 대부분 Point-to-Point 또는 Publish/Subscribe 방식의 메시징 서비스를 지원하였다.
       - JMS명세서에서는 각각의 분리된 도메인이나 동일한 도메인에서 메시징 서비스를 할 수 있도록 지원한다.
       - 독립적인 JMS 제공자는 하나 또는 양쪽의 도메인을 구현할 수 있으나 J2EE 제품 제공자는 반드시 양쪽 도메인을 구축해야만 한다.
       - JMS API를 사용하여 개발한 대부분의 애플리케이션은 Point-to-Point와 Publish/Subscribe도메인을 지원할 수 있다.
     
    3. Point-to-Point 메시징 도메인
       - Point-to-Point 방식의 메시징 도메인은 Queue, Sender, Receiver의 개념을 기본으로 하여 구성되어 있다.
       - 각각의 메세지는 지정된 Queue의 주소로 전달되고 전달 받으려는 클라이언트는 자신에게 전달된 메시지를 가지고 있는 Queue로부터 메시지를 받는다.
       - Point-to-Point 메시징 도메인의 특징
          - 각각의 메시지는 오직 하나의 소비자에게만 전달된다.
          - 메시지 Sender와 Receiver는 시간에 비의존적이다. 즉 Receiver는 Sender가 언제 메시지를 보냈는지에 상관없이 자신이 원할 때 메시지를 받는다.
          - Receiver는 큐에 성공적으로 메시지를 받았음을 알린다.
       - Point-to-Point 메시징 도메일을 사용하여 메시지를 전달하면 반드시 한 소비자에게만 메시지가 전달된다.
     
    4. Publish/Subscribe 메시징 도메인
       - Publish/Subscribe 방식의 메시징 도메인은 메시지를 전달하는 클라이언트가 인터넷 게시판과 같은 기능을 갖는 Topic이라는 목적지로 메시지를 전달한다.
       - Publisher와 Subscriber는 일반적으로 익명의 상대를 대상으로 하며 동적으로 메시지를 전달하거나 전달받을 수 있다.
       - 이 시스템은 다양한 Publisher가 다양한 Subscriber에게 메시지를 전달할 수 있고 토픽은 현재 자신에게 등록한 Subscriber에게   메시지를 전달한다.
       - Publish/Subscribe 메시징 도메인의 특징은 다음과 같다.
          - 각각의 메시지는 다양한 소비자에게 전달된다.
          - Publisher와 Subcriber는 시간에 의존적이다. 특정 토픽(Topic)에 등록한 Subscriber는 자신이 등록한 토픽에 전달된 메시지만을 받을 수가 있고, 메시지를 소비하기 위해서 반드시 Publisher에 연결된 상태이어야 한다.
           
    5. 메시지의 소비
       - 메시징 서비스 제품들은 기본적으로 비동식이다. 그러나 하나의 메시지는 동기식, 비동기식 모두에서 사용될 수 있다.
          - 동기식(Synchronously) : Subscriber또는 Receiver는 명시적으로 receive()메소드를 호출하여 목적지로부터 메시지를 받는다. 이 메소드의 호출은 메시지가 도착하거나 메시지가 도착하지 않았을때 지정된 시간까지 대기한다.
          - 비동기식(Asynchromously) : 클라이언트는 이벤트 리스너와 비슷한 메시지 리스너(MEssage Listener)를 통해 메시지를 전달받을 수 있다. 메시지 리스너는 목적지에 메시지가 도착하였을 때 onMessage() 메소드가 호출되어 메시지가 전달되었음을 알려준다.

    ##########################################
    # JMS API로 구성된 애플리케이션의 구성
    ##########################################
    - JMS애플리케이션은 다음과 같은 구성요소로 되어 있다.
       - 관리객체(Administered Object) : 커넥션 펙토리(Connection Factory)와 목적지(Destination)
       - 커넥션(Connection)
       - 세션(Session)
       - 메시지 생산자(Message Producer)
       - 메시지 소비자(Message Consumer)
       - 메시지(Message)

    1. 관리객체 (Administered Object)
       - JMS 애플리케이션에서 프로그래밍적인 요소보다 더 중요하게 관리되는 구성 요소가 커넥션 펙토리와 목적지라는 관리 객체이다.
       - 이들 객체의 생성과 관리는 JMS API에서 직접 구현하는 것이 아니라 JMS제공자에 의해서 관리된다.
       - 관리자는 JNDI 네임스페이스내에 이들 관리 객체를 구성하고 JMS 클라이언트는 JNDI API를 통해 등록된 JNDI네임스페이스를   검색할 수 있다.

    1.1 커넥션 팩토리(Connection Factory)
       - 커넥션 팩토리는 클라이언트가 JMS 서비스에 연결하기 위한 커넥션을 생성할 때 사용하는 객체이다.
       - 커넥션 팩토리는 관리자가 정의한 커넥션에 관련된 설정 매개 변수르르 캡슐화하고 있으며, 각각의 커넥션 팩토리는
         QueueConnectionFactory 또는 TopicConnectionFactory 인터페이스의 인스턴스이다.
       - JSM클라이언트는 프로그램 시작 부분에 JNDI API를 사용하여 커넥션 팩토리를 네이밍서비스에서 검색한다.
       - 검색된 커넥션 팩토리는 ConnectionFactory 객체로 캐스팅하여 사용되기도 하고 QueueConnectionFactory나
         TopicConnectionFactory 객체로 캐스팅하여 사용되기도 한다.
       - EX>
            Context ctx = new InitialContext();
            ConnectionFactory connectionFactory = (ConnectionFactory)ctx.lookup("jms/ConnectionFactory");
           
    1.2 목적지(Destination)
       - 목적지는 생성된 메시지가 저장되는 저장소로 그리고 메시지가 소비되는 곳으로 사용되는 객체이다.
       - 목적지는 Point-to-Point 메세징 도메인에서는 Queue, Publish/Subscribe 메시징 도메인에서는 Topic이라 부른다.
       - 애플리케이션 서버를 사용하여 목적지를 생성하려면 다음 두 가지 단계를 거쳐야 한다.
          - JNDI 목적지의 이름을 지정한 JMS 목적지 리소스를 생성한다.
          - JNDI 이름을 참조하는 물리적인 목적지를 사용한다.
       - 클라이언트 프로그램에서는 먼저 커넥션 팩토리를 네이밍 컨텍스트에서 검색하고 그런 다음에 목적지를 검색한다.
       - 목적지 객체는 Destination 타입으로 캐스팅되며, 적절한 다른 타입으로 캐스팅될 수도 있다.
       - Ex> Destination myDest = (Destination)ctx.lookup("jms/MyTopic");
               Topic myTopic = (Topic)myDest;
               or
               Queue myQueue = (Queue)ctx.lookup("jms/MyQueue");
              
    2. 커넥션(Connection)
       - 커넥션은 JMS 제공자를 이용한 가상의 커넥션을 캡슐화하고 있다.
       - 커넥션은 클라이언트와 제공자 서비스 데몬 사이를 TCP/IP 소켓을 이용하여 통신하고, 개발자는 커넥션을 사용하여 한 개 또는 여러개의 세션을 생성한다.
       - 커넥션은 ConnectionFactory 객체의 createConnection() 메소드를 호출하여 Connection인터페이스 타입으로 얻을 수 있다.
            Connection connection = connectionFactory.createConnection();
       - 애플리케이션이 완료되기 전에 생성했던 커넥션은 반드시 닫아야 한다.
            connection.close();
           
    3. 세션(Session)
       - 세션은 메시지를 생성하고 소비하는 단일 스레드 단위이다.
       - 세션은 메시지 리스너가 실행될 때 함께 작동하며, 메시지 생산자, 메시지 소비자 그리고 메시지를 생성할 때 세션을 사용할 수 있다.
       - 애플리케이션에서 메시지를 보내고 받기 위한 최소한의 단위를 트랜잭션이라 하는데 세션은 이런 트랜잭션을 기능을 제공한다.
       - 세션은 Session 인터페이스를 구현하고 Connection 객체의 createSession() 메소드를 호출하여 세션 객체를 생성할 수 있다.
             Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
       - 트랜잭션에 포함되는 세션을 생성하려면 다음과 같이 작성한다.
             Session session = connection.createSession(true, 0);
         
    4. 메시지 생산자(Message Producer)
       - 메시지 생산자는 목적지에 메시지를 전달하는 역할을 하는 객체이다.
       - 메시지 생산자는 MessageProducer 인터페이스를 구현한 객체로 MessageProducer를 생성하기 위해서는 Session 객체를 사용한다.
       - Ex> MessageProducer producer = session.createProducer(myQueue);
                MessageProducer producer = session.createProducer(myTopic);
       - 메시지 생성자를 생성한 다음에 send()메소드를 호출하여 메시지를 전달한다.
             producer.send(message);
       - createProducer()메소드에 null값을 지정하여 특정한 생성자를 할당하지 않을 수도 있다. 이렇게 메시지 목적지를 갖지 않는 메시지 생산자는 목적지를 지정하기 위해서 send() 메소드의 첫번째 매개 변수에 목적지를 지정해야 한다.
             MessageProducer anon_prod = session.createProducer(null);
             anon_prod.send(myQueue, message);
         
    5. 메시지 소비자(Message Consumer)
       - 메시지 소비자는 목적지에 전달된 메시지를 전달받는 역할을 하는 객체이다.
       - 메시지 소비자는 MessageConsumer 인터페이스를 구현한 객체로 메시지 생산자와 마찬가지로 세션에 의해서 생성된다.
       - 메시지 소비자는 JMS클라이언트가 JMS제공자를 이용하여 목적지에 클라이언트 자신을 등록할 수 있도록 해준다.
       - 목적지에 등록된 클라이언트만이 메시지를 전달받을 수 있으며, JMS제공자는 목적지에 등록된 메시지 소비자에게 목적지에 전달된 메시지를 전달하는 것을 관리하게 된다.
       - Ex> MessageConsumer consumer = session.createConsumer(myQueue);
                MessageConsumer consumer = session.createConsumer(myTopic);
       - 메시지 소비자가 생성된 다음에 이 메시지 소비자를 이용하여 메시지를 잔달받을 수 있으나 메시지는 커넥션이 연결된 다음 start() 메소드가 호출되기 전까지는 전달되지 않는다. 메시지 소비자가 동기적으로 메시지를 소비하기 위해서는 receive() 메소드가 사용되는데 start()메소드가 호출된 다음에는 언제든지 receive()메소드를 호출할 수 있다.
             MessageConsumer의 close()메소드를 사용하면 메시지의 소비자의 사용을 중지할 수 있다.
             connection.start();
             Message m = consumer.receive();
             connection.start();
             Message m = consumer.receive(1000); // time out after a second
       - 만약 비동기적으로 메시지를 소비하려면 메시지를 이벤트처럼 관리하는 메시지 리스너가 필요하다.
     
    5.1 메시지 리스터(Message Listener)
       - 메시지 리스너는 JMS API에서 사용되는 이벤트 핸들러로 비동기식으로 메시지를 전달받을 수 있게 해준다.
       - 메시지 리스너는 MessageListener 인터페이스를 구현해야 하며 MessageListener에는 onMessage()라는 단 하나의 이벤트
         메소드를 가지고 있다. 메시지가 목적지에 도착했을 때 작업하려는 내용을 onMessage()메소드에 작성하면 된다.
       - 메시지 리스너를 등록하기 위해서는 MessageConsumer의 setMessageListener()메소드를 이용한다.
            Listener myListener = new Listener();
            consumer.setMessageListener(myListener);
       - 메시지 리스너를 등록한 다음에는 Connection의 start()메소드를 호출하여 메시지 전송을 시작한다.
       - 메시지가 전달되기 시작하면 JMS 제공자는 메시지가 전달되었을 때 자동으로 메시지 리스너의 onMessage() 메소들 호출한다.
         onMessage() 메소드는 메시지를 매개 변수로 전달받는데 전달받은 메시지는 6가지(TextMessage, MapMessage,
         BytesMessage, StreamMessage, ObjectMessage, Message)의 메시지 타입 중 하나로 변환하여 사용할 수 있다.
        
    5.2 메시지 셀렉터(Message Selector)    
       - 애플리케이션에서 전달받은 메시지를 필터링(Filtering)할 필요가 있다면 JMS API의 메시지 셀렉터를 사용한다.
       - 메시지 셀렉터의 표현식은 문자열로 나타내는데 이 표현식은 SQL92조건절을 기반으로 해서 작성한다.
       - Ex> NewsType = '스포츠' OR NewsType = '독자의견'
       - createConsumer()와 createDurableSubsriber()메소드를 이용하여 메시지 소비자를 생성할 때 매개 변수로 메시지 셀렉터를 지정할 수 있다. 이렇게 메시지 셀렉터를 가지고 생성된 메시지 소비자는 메시지의 해더(Header)와 프로퍼티(Property)가 셀렉터와 일치하는 메시지만을 전달받게 된다.
         
    6. 메시지(Message)
       - JMS 애플리케이션의 최종 목적은 메시지를 생성한 다음에 다른 소프트웨어 애플리케이션으로 하여금 이 메시지를 소비하도록 하는데 있다.
       - JMS메시지는 Header, Property 그리고 Body 의 세부분으로 구성되어 있다. 이중 Header는 필수사항이고 나머지는 옵션이다.
          - Message Header(필수)
          - Message Property(옵션)
          - Message Body(옵션)
         
    6.1 메시지 헤더(Message Header)
       - JMS메시지 해더는 JMS클라이언트와 JMS제공자가 메시지를 확인하고 전달하기 위해 사용하는 몇가지 정의된 값을 가지고 있다.
       - 모든 메시지는 JMS 헤더 필드에 JMSMessageID라는 유일한 식별자를 가지고 있다.
       - JMSDestination이라는 헤더 필드는 메시지가 보내질 큐나 토픽을 나타낸다.
       - 각각의 헤더 필드는 모두 setter()/getter()메소드를 가지고 있으며 Message 인터페이스를 참조하여 이를 사용할 수 있다.
       - 대부분의 헤더 필드는 send() 또는 publish() 메소드에 의해서 자동으로 사용되는 데 반해서 클라이언트에 의해서 사용되기도 한다.


       ===============================================================
       JMS 메시지 헤더 필드
       ===============================================================
       헤더필드                                  사용되는 위치
       ==================      ==========================================
       JMSDestination                       send() 또는 publish()메소드
       JMSDeliveryMode                    send() 또는 publish()메소드
       JMSExpiration                         send() 또는 publish()메소드
       JMSPriority                              send() 또는 publish()메소드
       JMSMessageID                       send() 또는 publish()메소드
       JMSTimestamp                       send() 또는 publish()메소드
       JMSCorrelationID                   Client
       JMSReplyTo                            Client
       JMSType                                 Client
       JMSRedelivered                      JMS제공자
     
    6.2 메시지 프로퍼티(Message Property)
       - 메시지에 헤더 필드가 제공한 정보 외에 추가로 정보가 필요하면 메시지 프로퍼티를 생성하여 지정하면 된다.
       - 메시지 프로퍼티는 다른 메시지 시스템과 호환되어 사용될 수 있고 메시지 셀렉터에서 사용될 수 있다.
     
    6.3 메시지 바디(Message Body)
       - JMS API에는 6가지의 메소드 바디타입이 있다.
       - 다양한 형태의 데이터로 메시지 바디를 채울수 있도록 JMS API는 여러 메소드를 제공한다.
          Ex> TextMessage message = session.createTextMessage();
                message.setText(msg_text);  // msg_text is a String
                producer.send(message);
       - 소비하는 측에서는 메시지를 일반적인 Message인터페이스 타입으로 받는데 반드시 적절한 메시지 타입으로 캐스팅해야만
         메시지를 사용할 수 있다.
       - 캐스팅된 메시지의 내용을 얻기 위해서는 getText()메소드와 같은 getter()메소드를 이용한다.
          Ex> Message m = consumer.receive();
                if(m instanceof TextMessage){
                    TextMessage message = (TextMessage)m;
                   System.out.println("Reading message : " + message.getText());
                }else{
                    //Handle Error
                }
     
       ===============================================================
       JMS 메시지 타입
       ===============================================================
       메시지 타입                         메시지 내용
       =================   ============================================
       TextMessage                    java.lang.String 객체 타입의 메시지이다.
       MapMessage                    name/value를 쌍으로 갖는 타입의 메시지이다.
       ByteMessage                    바이트스트림의 메시지이다. 이 메시지 타입은 기존의 메시지 포멧과 매칭하기 위해서 메시지의
                                                내용을 인코딩(Encoding)할 때 사용한다.
       StreamMessage                자바에서 사용하는 기본 스트림 타입의 메시지이다.
       ObjectMessage                 자바에서 사용하는 직렬화된 객체 타입의 메시지이다.
       Message                           메시지 바디가 없이 헤더와 프로퍼티만으로 구성되어 있다. 메시지 바디가 필요하지 않을 때 사용한다.
     
    7. 예외처리
       - JMS API에서 사용되는 예외중 최상위 예외 클래스는 JMSException이다. JMSException 서브 클래스는 다음과 같다.
          - IllegalStateException
          - InvalidClientIDException
          - InvalidDestinationException
          - InvalidSelectorException
          - JMSSecurityException
          - MessageEOFException
          - MessageFormatException
          - MessageNotReadableException
          - MessageNotWriteableException
          - ResourceAllocationException
          - TransactionInProgressException
          - TransactionRolledBackException  


    ########################################
    # Sun Application 설정
    ########################################      

    - Sun Application Server 를 JMS제공자로 사용하기위해 다음 세가지를 설정한다. - 두 개의 커넥션 펙토리 (Queue/Topic) - 두 개의 물리적인 목적지 (Queue/Topic) - 두 개의 목적지 리소스 (Queue/Topic)

    - 커넥션 펙토리 설정 1. Admin Console을 실행한다 2. Java Message Service Resource > Connection Factory 노드 선택 3. JMS Connection Factory 페이지에서 "New" 버튼클릭 -> Create JMS Connection Factory 화면 이동 4. JNDI Name 필드에서 jms/QueueConnectionFactory 입력, Type 콤보박스에서 javax.jms.QueueConnectionFactory를     선택, Resource 항목은 Enabled Check한 후 "OK" 버튼으로 커넥션 펙토리를 저장한다. 5. 위와 같은 방법으로 jms/TopicConnectionFactory, javax.jms.TopicConnectionFactory를 생성한다.

    - 물리적 목적지 설정 1. Configuration > Java Message Service > Physical Destination 항목을 선택한다. 2. Physical Destination 항목에서 "New" 를 클릭 -> Create Physical Destination 페이지로 이동 3. Physical Destination Name 필드에 PhysicalQueue라고 입력. Type 콤보박스에서 Queue 선택. "OK" 버튼을 클릭하여    저장한다. 4. 위와 같은 방법으로 PhysicalTopic/topic을 생성한다.

    - 목적지 리소스 생성 1. JMS Resource > Destination Resource 으로 이동한다. 2. "New" 버튼을 클릭 -> Create JMS Destination Resource 페이지로 이동한다. 3. JNDI Name필드에 jms/Queue라고 입력. Type콤보박스에서 javax.jms.Queue를 선택하고 Resource Enabled항목으로     선택. Additional Property 항목의 Name 필드의 Value에 PhysicalQueue라고 입력한 후 "OK"버튼을 클릭하여 저장한다. 4. 위와 같은 방법으로 jms/Topic/javax.jms.Topic/Resource Enabled Check 선택, Name 필드의 Value에 PhysicalTopic     라고 입력한다.

    ########################################
    # 예제!!
    ########################################    

    /*
     * SimpleProducer.java
     *
     * Created on 2007년 3월 26일 (월), 오후 9:25
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */

    package simpleproducer;

    import javax.jms.ConnectionFactory;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.MessageProducer;
    import javax.naming.*;
    import javax.jms.*;

    /**
     *
     * @author Administrator
     */
    public class SimpleProducer {
       
        /** Creates a new instance of SimpleProducer */
        public SimpleProducer() {
        }
       
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            final int NUM_MSGS;
           
            if ((args.length < 1) || (args.length > 2))
            {
                System.out.println("Program take one or two arguments : <dest_name> [<number-of message>]");
                System.exit(1);
            }
           
            String destName = new String(args[0]);
            System.out.println("Destination name is " + destName);
           
            if (args.length == 2)
            {
                NUM_MSGS = (new Integer(args[1])).intValue();
            }
            else
            {
                NUM_MSGS = 1;
            }
           
            Context jndiContext = null;
           
            try
            {
                jndiContext = new InitialContext();
            }
            catch(NamingException e)
            {
                System.out.println("Could not create JNDI API context : " + e.toString());
                System.exit(1);
            }
           
            ConnectionFactory connectionFactory = null;
            Destination dest = null;
           
            try
            {
                connectionFactory = (ConnectionFactory)jndiContext.lookup("jms/QueueConnectionFactory");
                dest = (Destination) jndiContext.lookup(destName);
            }
            catch(Exception e)
            {
                System.out.println("JNDI API lookup failed : " + e.toString());
                e.printStackTrace();
                System.exit(1);
            }
           
            Connection connection = null;
            MessageProducer producer = null;
           
            try
            {
                connection = connectionFactory.createConnection();
               
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
               
                producer = session.createProducer(dest);
               
                TextMessage message = session.createTextMessage();
               
                for(int i = 0; i < NUM_MSGS; i++)
                {
                    message.setText("This is message " + (i + 1));
                    System.out.println("Sending message : " + message.getText());
                   
                    producer.send(message);
                }
            }
            catch(JMSException e)
            {
                System.out.println("Exception occurred : " + e.toString());
            }
            finally{
                if (connection != null)
                {
                    try{
                        connection.close();
                    }
                    catch(JMSException e)
                    {
                       
                    }
                }
            }
           
        }
       
    }



    /*
     * SimpleSynchConsumer.java
     *
     * Created on 2007년 3월 26일 (월), 오후 10:21
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */

    package simplesynchconsumer;

    import javax.jms.*;
    import javax.naming.*;

    /**
     *
     * @author Administrator
     */
    public class SimpleSynchConsumer {
       
        /** Creates a new instance of SimpleSynchConsumer */
        public SimpleSynchConsumer() {
        }
       
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
           
            String destName = null;
            Context jndiContext = null;
            ConnectionFactory connectionFactory = null;
            Connection connection = null;
            Session session = null;
            Destination dest = null;
            MessageConsumer consumer = null;
            TextMessage message = null;
           
            if(args.length != 1)
            {
                System.out.println("Program takes one argument : <dest_name>");
                System.exit(1);
            }
           
            destName = new String(args[0]);
            System.out.println("Destination name is " + destName);
           
            try
            {
                jndiContext = new InitialContext();
            }
            catch(NamingException e)
            {
                System.out.println("Could not create JNDI API context : " + e.toString());
                System.exit(1);
            }
           
            try
            {
                connectionFactory = (ConnectionFactory)jndiContext.lookup("jms/QueueConnectionFactory");
                dest = (Destination)jndiContext.lookup(destName);
            }
            catch(Exception e)
            {
                System.out.println("JNDI API lookup failed : " + e.toString());
                System.exit(1);
            }
           
            try
            {
                connection = connectionFactory.createConnection();
               
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
               
                consumer = session.createConsumer(dest);
               
                connection.start();
               
                while(true)
                {
                    Message m = consumer.receive(1);
                   
                    if (m != null)
                    {
                        if (m instanceof TextMessage)
                        {
                            message = (TextMessage)m;
                           
                            System.out.println("Reading message : " + message.getText());
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch(JMSException e)
            {
                System.out.println("Exception occured : " + e.toString());
            }
            finally
            {
                if (connection != null)
                {
                    try{
                        connection.close();
                    }
                    catch(JMSException e)
                    {
                       
                    }
                }
            }
        }
       
    }



    /*
     * SimpleAsynchConsumer.java
     *
     * Created on 2007년 3월 26일 (월), 오후 11:02
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */

    package simpleasynchconsumer;

    import javax.jms.*;
    import javax.naming.*;
    import java.io.*;

    /**
     *
     * @author Administrator
     */
    public class SimpleAsynchConsumer {
       
        /** Creates a new instance of SimpleAsynchConsumer */
        public SimpleAsynchConsumer() {
        }
       
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
           
            String destName = null;
            Context jndiContext = null;
            ConnectionFactory connectionFactory = null;
            Connection connection = null;
            Session session = null;
            Destination dest = null;
            MessageConsumer consumer = null;
            TextListener listener = null;
            TextMessage message = null;
            InputStreamReader inputStreamReader = null;
            char answer = '\0';
           
            if (args.length != 1)
            {
                System.out.println("Program takes one argument : <dest_name>");
                System.exit(1);
            }
           
            destName = new String(args[0]);
            System.out.println("Destination name is " + destName);
           
            try
            {
                jndiContext = new InitialContext();
            }
            catch(NamingException e)
            {
                System.out.println("Could not create JNDI API context : " + e.toString());
                System.exit(1);
            }
           
            try
            {
                connectionFactory = (ConnectionFactory)jndiContext.lookup("jms/QueueConnectionFactory");
                dest = (Destination)jndiContext.lookup(destName);
            }
            catch(Exception e){
                System.out.println("JNDI API lookup failed : " + e.toString());
                System.exit(1);
            }
           
            try
            {
                connection = connectionFactory.createConnection();
               
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
               
                consumer = session.createConsumer(dest);
               
                listener = new TextListener();
               
                consumer.setMessageListener(listener);
               
                connection.start();
               
                System.out.println("To end program, type Q or q, then <return>");
               
                inputStreamReader = new InputStreamReader(System.in);
               
                while(!((answer == 'q') || (answer == 'Q')))
                {
                    try
                    {
                        answer = (char)inputStreamReader.read();
                    }
                    catch(IOException e)
                    {
                        System.out.println("I/O exception : " + e.toString());
                    }
                }
            }
            catch(JMSException e)
            {
                System.out.println("Exception occured : " + e.toString());
            }
            finally
            {
                if (connection != null)
                {
                    try
                    {
                        connection.close();
                    }
                    catch(JMSException e)
                    {              }
                }
            }
        }
       
    }


    /*
     * TextListener.java
     *
     * Created on 2007년 3월 26일 (월), 오후 11:02
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */

    package simpleasynchconsumer;

    import java.awt.font.TextMeasurer;
    import javax.jms.*;

    /**
     *
     * @author Administrator
     */
    public class TextListener implements MessageListener {
       
        /** Creates a new instance of TextListener */
        public TextListener() {
        }
       
        public void onMessage(Message message)
        {
            TextMessage msg = null;
           
            try
            {
                if (message instanceof TextMessage)
                {
                    msg = (TextMessage)message;
                   
                    System.out.println("Reading message : " + msg.getText());
                }
                else
                {
                    System.out.println("Message is not a TextMessage");
                }
            }
            catch(JMSException e)
            {
                System.out.println("JMSException in onMessage() : " + e.toString());
            }
            catch(Throwable t)
            {
                System.out.println("Exception in onMessage() : " + t.getMessage());
            }
        }
       
    }
Designed by Tistory.