Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This docs is for v0.2+

Changes

v0.2

  1. It is no longer a mandatory to provide a JMS ConnectionFactory. For a single JVM simple usage, you may use the default in-memory, non-persistent ActiveMQ connection factory, or you could configure your JMSProvider in several ways.
  2. The library is no longer used as a Groovy Category. The Groovy Category are hidden. There are a few different ways to use:
    Code Block
    // 1
    jms{ //require static import of groovy.jms.JMS.jms
     // your jms code
    }
    
    // 2
    def jms = new JMS(){
     // your jms code
    }
    
    // and for further execution
    jms.run{
     // more jms code
    }
    
    
    // 3
    def jms = new JMS()
     jms.xxx ; // this is for using the Groovy Messaging Service API
     jms.close() //must be closed manually if JMS code are not executed in the JMS Context♠
    
  3. The base Category API are slightly modified and are refactored to the JMSCoreCategory. Two sets of new APIs: GroovyJMS API and Groovy Messaging Service API are provided. The latter are designed base on the Groovy Sql.

Usage

Concepts

  • GroovyJMS Execution Context
    • GroovyJMS mainly provide an execution context that you can use enhanced JMS API and convenient methods, and access to implicit variables
      Code Block
      new JMS(){
       // inside the execution context, where magics occur
      }
      
      import static groovy.jms.JMS.jms;
      jms{
       // inside the execution context, where magics occur
      }
      
    • GroovyJMS is based on JMS and preserve any JMS concepts and keywords.  You could mix the usage of GroovyJMS API and JMS API in the execution context.
  • GroovyJMS Core API
    • GroovyJMS Core API is based on the JMSCoreCategory, and shall be used in Execution Context. APIs are provided for JMS Resource and Destination
    • JMS Resource - ConnectionFactory, Connection and Session. You could create any of them outside the execution context and pass to the constructor of GroovyJMS, or you could use the implicitly created instances.
      • Refer to the next section about JMS ConnectionFactory
      • Inside the execution context, getConnection() and getSession() methods are attached to any class, so you could "connection" and "session" like an pre-declared variable. The connection and session are attached to a threadlocal JMS instance
        Code Block
        new JMS(){
         println connection; // by default: ActiveMQConnection {id=ID:hostname-1212-1223775533432-2:0,clientId=ID:hostname-1212-1223775533432-3:0,started=false}
         println session; // by default: ActiveMQSession {id=ID:hostname-1212-1223775533432-2:0:1,started=false}
        }
        
      • JMS Resources are used interchangeably when creating lower level JMS Resource
        Code Block
        def factory; //injected JMS ConnectionFactory
        new JMS(){
         def conn0 = factory.connect(), conn1 = connection
         def session0 = factory.session(), session1 = connection.session()
        }
        
      • GroovyJMS provides high level API that use a single connection and session per thread. Unless you want a fine-grained control over the re-use of Connection and Session, it is not necessary to care about these resources.
    • JMS Destination - Queue, Topic
      • There are two types of JMS destination. GroovyJMS provides high level API to operate on any Queue or Topic, unless you need to get a reference for JMS Destination, you don't need to care about JMS Destinations.
      • Short API are provided for creating JMS Destinations. Similar to JMS Resource, calling subject is interchangable.
        Code Block
        def factory; //injected JMS ConnectionFactory
        new JMS(){
         def topic0 = factory.topic(), topic1 = connection.topic(), topic2 = session.topic()
         def queue0 = factory.queue(), topic1 = connection.queue(), topic2 = session.queue()
        }
        
      • The return value of topic() and queue() are JMS Topic and Queue respectively. However, in GroovyJMS Execution Context, you could use some operation APIs such as send(), receive() etc. directly on JMS Destination.
      • APIs
        Code Block
        topic.subscribe( subscriptionName:'x', messageSelector:'y', noLocal:true, durable:false) ; //by default, durable is true, subscriptionName is generated unique name, messageSelector is null, noLocal is false, durable is true
        
    • Message - MapMessage
      • mapMessage.toMap()
  • GroovyJMS API
    • GroovyJMS API is based on the JMSCoreCategory, and shall be used in Execution Context
    • For simple usage, it is the only thing you need to learn. GroovyJMS API uses keywords from JMS API.
      • "send" and "receive" for Queue messages
      • "publish" and "subscribe" for Topic messages
    • You could call the API in two style
      • Message as subject, and sendTo
        Code Block
        "Hello world".publishTo "topics/test"
        [hello:'world'].publishTo "topics/test"
        "Hello world".sendTo "queue/test"
        [hello:'world'].sendTo "queue/test"
        
        Ideas:
        "abc".send() // send to the last used queue/topic
        ? allow user to configure a boolean to reverse the use of send() ?
        
      • Or use the destination/Message as subject
        Code Block
        "topics/test".publish "Hello world"
        "topics/test".publish [hello:'world']
        
        "queue/test".send "Hello world"
        "queue/test".send [hello:'world']
        "queue/test".send( "Hello world", [replyTo:'queue/replyQueue'])
        
        "topic/test".subscribe(){ println it.text }
        "topic/test".subscribe(
        //"topics/test".subscribe().with{ println it.text } // "topic".subscribe() [w/o closure] is a synonym of connection.topic()
        "queue/test".receive() //to be implemented
        "queue/test".receiveAll() //to be implemented
        "queue/test".receiveAll( within:200.ms) //to be implemented
        
        Message receivedMessage = "queue/test".recieve()
        receivedMessage.reply "this is my answer"
        
      • For certain operations, you don't even need a subject
        Code Block
        subscribe("topics/test"){ println it.text }
        //subscribe("topics/test").with{ println it.text } //synonym
        def message = receive("queue/test")
        def messages = receiveAll("queue/text")
        
        //subscribeTo("topics/test").with{ println it.text } //subscribeTo is a synonym of connection.topic()
        //receive("queue/test").with{} //receiveFrom is a synonym of connection.queue() , with is the default with{} in Groovy, it is optional
        //def messages = receiveAllFrom("queue/test").with{ it } //receiveFrom is a synonym of connection.queue().receiveAll()
        //receiveAllFrom("queue/test").each{ } //directly use the iterator
        
        //other Ideas, using map
        send 'toTopic':'topic/test', 'message',[key:'value'], 'from':'fromclient'
        
      • API in a spreadsheet [http://www.editgrid.com/publish/html/user/mingfai/24976908/A2:M24]
  • Groovy Messaging Service API
    • Groovy Messaging Service API do not need to run in the Execution Context.
    • Groovy Messaging Service API is designed base on the Groovy core Sql API.

      Groovy SQL

      Possible JMS Usage

      Remarks/Comment

      Sql.newInstance()

      JMS.newInstance(jmsConnectionFactory)

      or just use new JMS()

      sql.eachRow

      jms.eachMessage("myQueue"){m-> }
      jms.eachMessage("myQueue", [within:100]){}

      jms.reply() could be used inside the closure

      reply is not implemented

      sql.firstRow

      jms.firstMessage("myQueue") { println it.text
      }

      jms.onMessage(topic:"mytopic"){ m -> }
      jms.onMessage(topic: "mytopic",durable:false){m -> } 
      jms.onMessage(queue:"myQueue"){ m -> }
      jms.onMessage(queue:"myQueue",topic: "mytopic"){ m -> }  //subscribe queue and topic at the same time

      //onMessage supports only one listener per session; if you need multiple subscription, use core API subscribe method and specific different subscriptionName

      jms.onMessage( topic: ['topic0', 'topic1']{ m -> }
      jms.onMessage( queue: ['queue0', 'qeueu1']{ m -> }
      jms.onMessage( topic:'mytopic', queue: ['queue0', 'qeueu1']{ m -> }

      jms.stopMessage( topic:"myTopic") // unsubscribe the listener
      jms.stopMessage( topic:['myTopic','myTopic2']) //TODO not implemented

      sql.execute()

      def result = jms.receive( fromQueue:'myQueue', within:1000)
      jms.receive( fromQueue: 'myQueue', within:1000)
      { println it }
      jms.receive( fromQueue:['queue0','queue1'], within:1000, with:
      { println it})

      fromTopic and fromQueue could be used together
      fromQueue always call receiveAll (to be enhanced to take a parameter to return only 1 message)
      if fromQueue has more than one queue, it return all messages of all queues
      fromTopic is asynchronous durable subscription, if both fromQueue and fromTopic are used together, any immediately available messages in any fromQueue will return first, and new message will be delivered to the same with closure in a later time
      either use jms.receive([:]){ }  or jms.receive([xxx:yyy, with:{}]) ; the former override the later
      within is a per queue timeout interval, not total; if there are more than one queue, each are retrieved in sequence

      sql.executeUpdate()

      jms.send( toTopic:'myTopic', message:[key:value], replyTo:'')

      toTopic and toQueue could be used together
      toTopic and toQueue support collection

    • All return value or closure handler result are JMS Message. It might be changed to String, Map, Byte[], Stream and Object in the future.
    • Similar to Sql, fine-grained control over connection/session could be done by passing in a JMS Connection or Session in the JMS.newInstance(), and user has to close the session/connection themselves

JMS Connection Factory

To use GroovyJMS, you need to decide which JMS implementation you'll use. There are several options:

  1. use the default in-memory, not-persistent ActiveMQ broker and connection factory, this is created by the ActiveMQJMSProvider class. Notice that the ActiveMQJMSProvider will start a ActiveMQ broker if it is not existed already, and will add a "vm://localhost" transport connector URL if not existed. In this case, the syntax is as simple as:
    Code Block
    new JMS(){
     // your jms code
    }
    
  2. Provide a JMSProvider by
    1. specific a "groovy.jms.provider" system property that point to a class that implements groovy.jms.provider.JMSProvider
    2. set a JMSProvider to the JMS.provider static variable, e.g.
      Code Block
      JMS.provider = { return new ActiveMQConnectionFactory("vm://localhost") } as JMSProvider
      
  3. Provide Connection Factory or Connection in runtime. it is the most recommended approach. You may utilize your JEE container or dependency injection framework to inject the required JMS resources to your class, and support the connection or factory to GroovyJMS.
    Code Block
    def myConnection; //injected
    new JMS( myConnection ){
     // your jms code
    }
    
    // OR
    def myConnectionFactory; //injected
    new JMS( myConnectionFactory){
     // your jms code
    }
    

So how cool is GroovyJMS in compare to JMS?

  • simplified api
  • subscribe to multiple topics and queues at the same time
  • simple listener implementation by using Closure
  • Groovish API , e.g. jms.eachMessage{}, jms.onMessage{}
  • English language style api: jms.send toQueue:'myQueue',message:'hello world'
  • etc.

Other important information

  • autoClose
    • by default, all connection are closed at the end of an execution context, or after any operation for Groovy Messaging Service API.
    • For Groovy Messaging Service API, if you need  to do more than one operation, you have to set autoClose to false, and call close() explicitly
      Code Block
      def jms = JMS.newInstance()
      jms.setAutoClose(false)
      JMS.close()
      
    • When using in execution context, it's unommon to disable autoClose. As one of the purpose of the execution context is to autoClose resource for you. If you need to use execution context and want to disable autoClose, one of the ways is:
      Code Block
      def jms = new JMS(){
       jms.setAutoClose(false)  
       // your jms code
      }
      

    • Or you'd better directly use the JMS Category without setting up an execution context.
      Code Block
      use(JMSCategory){
       jms.session() ; // notice that you need to establish a session before doing anything with JMSCategory
       "queue".send("message")
       assertNotNull("queue".receive(waitTime:100))
      }
      

Unsupported Features or Limitation

  • nested usage is not supported yet. you may still use the lib in nested manner but you have manage the Connection and Session carefully.
    • For example:
      Code Block
      def connFactory, conn
       new JMS(conn){
          // outer JMS code
         new JMS(conn){
           // inner JMS code
         }
         //exception may be thrown at the end as the connection is closed
       }
      
    • you are recommended to avoid nestled usage. If you use it, try to use a multiple connection.
  • There is no support for transaction. all messages are auto-committed