<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE entities [
<!ENTITY %  entities SYSTEM  "commonEntities.xml">
%entities;
]>
<!--

 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.

-->

<section id="Java-Broker-Queues-OtherTypes">
  <title>Queue Types</title>

  <section role="h2" id="Java-Broker-Queues-OtherTypes-Introduction">
    <title>Introduction</title>
    <para> In addition to the standard queue type where messages are delivered in the same order
      that they were sent, the Java Broker supports three additional queue types which allows for
      alternative delivery behaviours. These are
      <link linkend="Java-Broker-Queues-OtherTypes-Priority">priority-queues</link>,
      <link linkend="Java-Broker-Queues-OtherTypes-Sorted">sorted-queues</link>-,
      <link linkend="Java-Broker-Queues-OtherTypes-LVQ">last-value-queues</link> (LVQs).
      Additionally, Java Broker supports <link linkend="Java-Broker-Queues-OtherTypes-Message-Grouping">message grouping</link>.
    </para>
    <para> In the following sections, the semantics of each queue type is described, followed by a
      description of how instances of these queue can be created via <link
        linkend="Java-Broker-Queues-OtherTypes-CreateUsingConfig">configuration</link>, <link
        linkend="Java-Broker-Queues-OtherTypes-CreateUsingJmsOrJmx">programmatically</link> or
        <link linkend="Java-Broker-Queues-OtherTypes-CreateUsingManagement">Web Management Console</link>.</para>
    <para>The final section discusses the importance of using a <link
        linkend="Java-Broker-Queues-OtherTypes-SetLowPrefetch">low client pre-fetch</link> with these queued.
    </para>
  </section>

  <section role="h2" id="Java-Broker-Queues-OtherTypes-Priority">
    <title>Priority Queues</title>
    <para>In a priority queue, messages on the queue are delivered in an order determined by the
        <ulink url="&oracleJeeDocUrl;javax/jms/Message.html#getJMSPriority()">JMS priority message
        header</ulink> within the message. By default Qpid supports the 10 priority levels mandated
      by JMS, with priority value 0 as the lowest priority and 9 as the highest. </para>
    <para>It is possible to reduce the effective number of priorities if desired.</para>
    <para>JMS defines the <ulink url="&oracleJeeDocUrl;javax/jms/Message.html#DEFAULT_PRIORITY">
        default message priority</ulink> as 4. Messages sent without a specified priority use this
      default. </para>
  </section>
  <section role="h2" id="Java-Broker-Queues-OtherTypes-Sorted">
    <title>Sorted Queues</title>
    <para>Sorted queues allow the message delivery order to be determined by value of an arbitrary
        <ulink url="&oracleJeeDocUrl;javax/jms/Message.html#getStringProperty()">JMS message
        property</ulink>. Sort order is alpha-numeric and the property value must have a type
      java.lang.String.</para>
    <para>Messages sent to a sorted queue without the specified JMS message property will be
      inserted into the 'last' position in the queue.</para>
  </section>
  <section role="h2" id="Java-Broker-Queues-OtherTypes-LVQ">
    <title>Last Value Queues (LVQ)</title>
    <para>LVQs (or conflation queues) are special queues that automatically discard any message when
      a newer message arrives with the same key value. The key is specified by arbitrary <ulink
        url="&oracleJeeDocUrl;javax/jms/Message.html#getPropertyNames()">JMS message
        property</ulink>.</para>
    <para>An example of an LVQ might be where a queue represents prices on a stock exchange: when
      you first consume from the queue you get the latest quote for each stock, and then as new
      prices come in you are sent only these updates. </para>
    <para>Like other queues, LVQs can either be browsed or consumed from. When browsing an
      individual subscriber does not remove the message from the queue when receiving it. This
      allows for many subscriptions to browse the same LVQ (i.e. you do not need to create and bind
      a separate LVQ for each subscriber who wishes to receive the contents of the LVQ).</para>
    <para>Messages sent to an LVQ without the specified property will be delivered as normal and
      will never be "replaced".</para>
  </section>
  <section role="h2" id="Java-Broker-Queues-OtherTypes-Create">
    <title>Creating a Priority, Sorted or LVQ Queue</title>
    <para>To create a priority, sorted or LVQ queue, it can be defined in the virtualhost
      configuration file, can be created programmtically from a client via AMQP (using
      an extension to JMS), using JMX, using REST interfaces or created in Web Management Console.
      These methods are described below. </para>
    <para>Once a queue is created you cannot change its type (without deleting it and re-creating).
      Also note you cannot currently mix the natures of these queue types, for instance, you cannot
      define a queue which it both an LVQ and a priority-queue.</para>
    <section role="h2" id="Java-Broker-Queues-OtherTypes-CreateUsingManagement">
      <title>Using Web Management Console</title>
      <para>On clicking on "Add Queue" button on Virtual Host tab the pop-up dialog to create a queue is displayed.</para>
      <para>For a Simple queue a Queue Type "Standard" should be selected</para>
      <para>For a Priority queue a Queue Type "Priority" and the priority value (10 by default) should be selected.</para>
      <para>For a Sorted queue a Queue Type "Sorted" and Sort Message Property should be specified.</para>
      <para>For a LVQ queue a Queue Type "LVQ" and LVQ Message Property should be specified.</para>
      <para>Additionally, for each type of the queue Flow Control Thresholds and Alert Thresholds can be specified in optional fields.</para>
      <para>Also, a Dead Letter Queue can be configured for the Queue by checking "Create DLQ" check box.
      The maximum number of delivery retries before message is sent to the DLQ can be specified in "Maximum Delivery Retries" field.
      However, configuring of maximum delivery retries on a queue without DLQ(AlternateExchange) will result in messages
      being discarded after the limit is reached.</para>
    </section>
    <section role="h2" id="Java-Broker-Queues-OtherTypes-CreateUsingJmsOrJmx">
      <title>Using JMX or AMQP</title>
      <para>To create a priority, sorted or LVQ queue programmatically from JMX or using a Qpid
        extension to JMS, pass the appropriate queue-declare arguments.</para>
      <table>
        <title>Queue-declare arguments understood for priority, sorted and LVQ queues</title>
        <tgroup cols="4">
          <thead>
            <row>
              <entry>Queue type</entry>
              <entry>Argument name</entry>
              <entry>Argument name</entry>
              <entry>Argument Description</entry>
            </row>
          </thead>
          <tbody>
            <row>
              <entry>priority</entry>
              <entry>x-qpid-priorities</entry>
              <entry>java.lang.Integer</entry>
              <entry>Specifies a priority queue with given number priorities</entry>
            </row>
            <row>
              <entry>sorted</entry>
              <entry>qpid.queue_sort_key</entry>
              <entry>java.lang.String</entry>
              <entry>Specifies sorted queue with given message property used to sort the
                entries</entry>
            </row>
            <row>
              <entry>lvq</entry>
              <entry>qpid.last_value_queue_key</entry>
              <entry>java.lang.String</entry>
              <entry>Specifies lvq queue with given message property used to conflate the
                entries</entry>
            </row>
          </tbody>
        </tgroup>
      </table>
      <para>The following example illustrates the creation of the a LVQ queue from a
        javax.jms.Session object. Note that this utilises a Qpid specific extension to JMS and
        involves casting the session object back to its Qpid base-class.</para>
      <example>
        <title>Creation of an LVQ using the Qpid extension to JMS</title>
        <programlisting><![CDATA[Map<String,Object> arguments = new HashMap<String, Object>();
arguments.put("qpid.last_value_queue_key","ISIN");
AMQDestination amqQueue = (AMQDestination) context.lookup("myqueue");
((AMQSession<?,?>) session).createQueue(
        AMQShortString.valueOf(amqQueue.getQueueName()),
        amqQueue.isAutoDelete(),
        amqQueue.isDurable(),
        amqQueue.isExclusive(),
        arguments);
]]></programlisting>

      </example>
      <para> The following example illustrates the creation of the sorted queue from a the JMX
        interface using the ManagedBroker interface. </para>
      <example>
        <title>Creation of a sorted queue using JMX</title>
        <programlisting><![CDATA[Map<String, Object> environment = new HashMap<String, Object>();
environment.put(JMXConnector.CREDENTIALS, new String[] {"admin","password"});
// Connect to service
JMXServiceURL url =  new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:8999/jmxrmi");
JMXConnector jmxConnector = JMXConnectorFactory.connect(url, environment);
MBeanServerConnection mbsc =  jmxConnector.getMBeanServerConnection();
// Object name for ManagedBroker for virtualhost myvhost
ObjectName objectName = new ObjectName("org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=myvhost");
// Get the ManagedBroker object
ManagedBroker managedBroker = JMX.newMBeanProxy(mbsc, objectName, ManagedBroker.class);;

// Create the queue passing arguments
Map<String,Object> arguments = new HashMap<String, Object>();
arguments.put("qpid.queue_sort_key","myheader");
managedBroker.createNewQueue("myqueue", null, true, arguments);]]></programlisting>
      </example>
    </section>
    <section role="h2" id="Java-Broker-Queues-OtherTypes-CreateUsingConfig">
        <title>Using configuration</title>
        <para>How to declare queues in the Virtual Host configuration file is described in <xref linkend="Java-Broker-Virtual-Host-Declare-Queues"/>.</para>
    </section>
  </section>

  <section role="h2" id="Java-Broker-Queues-OtherTypes-Binding">
    <title>Binding queues to exchanges</title>
    <para>Queues can be bound to the broker exchanges in the virtualhost
      configuration file or programmtically from a client using AMQP bind API (using
      an extension to JMS), using JMX API, using REST interfaces or Web Management Console.</para>
    <para>A queue can be bound to different exchanges at the same time.
    Also, a queue can be bound to the same exchange multiple times.
    Differenent binding keys can be used to bind a queue to the same topic or direct exchanges.</para>
    <para>Binding attributes can be specified on binding creation to allow filtering of messages accepted by the queue using a selector expression
    or/and specifying whether messages published by its own connection should be delivered to it.</para>
    <section role="h3" id="Java-Broker-Queues-OtherTypes-BindingUsingManagement">
      <title>Using Web Management Console</title>
      <para>A queue can be bound to an exchange by clicking on "Add Binding" button on a Queue tab or an Exchange tab.</para>
    </section>
    <section role="h3" id="Java-Broker-Queues-OtherTypes-BindingUsingJmsOrJmx">
      <title>Using JMX or AMQP</title>
      <para>The following example illustrates the creation of queue binding to topic exchange with JMS client.</para>
      <example>
        <title>Binding a queue using JMS</title>
        <programlisting><![CDATA[ConnectionFactory connectionFactory = ...
Connection connection = connectionFactory.createConnection();
AMQSession<?, ?> session = (AMQSession<?,?>)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

...

AMQShortString queueName = new AMQShortString("testQueue");
AMQShortString routingKey = new AMQShortString("testRoutingKey");
AMQDestination destination = (AMQDestination) session.createQueue(queueName.asString());

...

// binding arguments
Map<String, Object> arguments = new HashMap<String, Object>();
arguments.put("x-filter-jms-selector", "application='app1'");

// create binding
session.bindQueue(queueName, routingKey, FieldTable.convertToFieldTable(arguments),
    new AMQShortString("amq.topic"), destination);]]></programlisting>
      </example>
      <para> The following example illustrates the creation of queue binding to topic exchange with JMX
        interface using the ManagedExchange interface. </para>
      <example>
        <title>Binding a queue using JMX</title>
        <programlisting><![CDATA[Map<String, Object> environment = new HashMap<String, Object>();
environment.put(JMXConnector.CREDENTIALS, new String[] {"admin","password"});

// Connect to service
JMXServiceURL url =  new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:8999/jmxrmi");
JMXConnector jmxConnector = JMXConnectorFactory.connect(url, environment);
MBeanServerConnection mbsc =  jmxConnector.getMBeanServerConnection();

// Object name for topic Exchange MBean for virtualhost 'default'
ObjectName objectName = new ObjectName("org.apache.qpid:type=VirtualHost.Exchange,"
    + "VirtualHost=\"default\",name=\"amq.topic\",ExchangeType=topic");

// Get the ManagedExchange object
ManagedExchange topicExchange = JMX.newMBeanProxy(mbsc, objectName, ManagedExchange.class);;

// Create the binding arguments
Map<String,Object> arguments = new HashMap<String, Object>();
arguments.put("x-filter-jms-selector", "application='app1'");

// create binding
topicExchange.createNewBinding("queue", "testBindingKey", arguments);]]></programlisting>
      </example>
    </section>
    <section role="h3" id="Java-Broker-Queues-OtherTypes-BindingUsingConfig">
        <title>Using configuration</title>
        <para>How to bind queues in the Virtual Host configuration file is shown in <xref linkend="Java-Broker-Virtual-Host-Binding-Queue"/>.</para>
    </section>
  </section>

  <section role="h2" id="Java-Broker-Queues-OtherTypes-Message-Grouping">
    <title>
      Messaging Grouping
    </title>
    <para>
      The broker allows messaging applications to classify a set of related messages as
      belonging to a group.  This allows a message producer to indicate to the consumer
      that a group of messages should be considered a single logical operation with
      respect to the application.
    </para>
    <para>
      The broker can use this group identification to enforce policies controlling how
      messages from a given group can be distributed to consumers.  For instance, the
      broker can be configured to guarantee all the messages from a particular group are
      processed in order across multiple consumers.
    </para>
    <para>
      For example, assume we have a shopping application that manages items in a virtual
      shopping cart.  A user may add an item to their shopping cart, then change their
      mind and remove it.  If the application sends an <emphasis>add</emphasis> message to the broker,
      immediately followed by a <emphasis>remove</emphasis> message, they will be queued in the proper
      order - <emphasis>add</emphasis>, followed by <emphasis>remove</emphasis>.
    </para>
    <para>
      However, if there are multiple consumers, it is possible that once a consumer
      acquires the <emphasis>add</emphasis> message, a different consumer may acquire the
      <emphasis>remove</emphasis> message.  This allows both messages to be processed in parallel,
      which could result in a "race" where the <emphasis>remove</emphasis> operation is incorrectly
      performed before the <emphasis>add</emphasis> operation.
    </para>
    <section role="h3" id="Java-Broker-Queues-OtherTypes-GroupingMessages">
      <title>
        Grouping Messages
      </title>
      <para>
        In order to group messages, the application would designate a particular
        message header as containing a message's <emphasis>group identifier</emphasis>.  The group
        identifier stored in that header field would be a string value set by the message
        producer.  Messages from the same group would have the same group identifier
        value. The key that identifies the header must also be known to the message
        consumers.  This allows the consumers to determine a message's assigned group.
      </para>
      <para>
        The header that is used to hold the group identifier, as well as the values used
        as group identifiers, are totally under control of the application.
      </para>
    </section>
    <section role="h3" id="Java-Broker-Queues-OtherTypes-BrokerRole">
      <title>
        The Role of the Broker in Message Grouping
      </title>
      <para>
        The broker will apply the following processing on each grouped message:
        <itemizedlist>
          <listitem>Enqueue a received message on the destination queue.</listitem>
          <listitem>Determine the message's group by examining the message's group identifier header.</listitem>
          <listitem>Enforce <emphasis>consumption ordering</emphasis> among messages belonging
          to the same group. <emphasis>Consumption ordering</emphasis> means one of two things
          depending on how the queue has been configured.
            <itemizedlist>
              <listitem>In default mode, each group is assigned to a consumer for
              the lifetime of the consumer.</listitem>
              <listitem>In C++ compatibility mode (which gives the same behaviour
              as the C++ Qpid Broker), the Broker enforces a looser guarantee, nameley that all the
              <emphasis>currently unacknowledged messages</emphasis> in a group will be sent to the
              same consumer.  This means that only one consumer can be processing messages from a particular
              group at a given time.  When the consumer acknowledges all of its acquired
              messages, then the broker <emphasis>may</emphasis> pass the next pending message
              from that group to a different consumer.</listitem>
            </itemizedlist>
          </listitem>
        </itemizedlist>
      </para>
      <para>
        The absence of a value in the designated header field for grouping as treated as indicative
        of a lack of desire for the message to be grouped. Messages with such a lack of a value will
        be distributed to any available consumer.
      </para>
      <para>
        Note that message grouping has no effect on queue browsers.
      </para>
      <para>
        Note well that distinct message groups would not block each other from delivery.
        For example, assume a queue contains messages from two different message groups -
        say group "A" and group "B" - and they are enqueued such that "A"'s messages are
        in front of "B". If the first message of group "A" is in the process of being
        consumed by a client, then the remaining "A" messages are blocked, but the
        messages of the "B" group are available for consumption by other consumers - even
        though it is "behind" group "A" in the queue.
      </para>
    </section>
    <section role="h3" id="Java-Broker-Queues-OtherTypes-BrokerConfig">
      <title>
        Broker Message Grouping Configuration
      </title>
      <para>
        In order for the broker to determine a message's group, the key for the header
        that contains the group identifier must be provided to the broker via
        configuration.  This is done on a per-queue basis, when the queue is first
        configured.
      </para>
      <para>
        This means that message group classification is determined by the message's destination
        queue.
      </para>
      <para>
        Specifically, the queue "holds" the header key that is used to find the message's
        group identifier.  All messages arriving at the queue are expected to use the same
        header key for holding the identifer.  Once the message is enqueued, the broker
        looks up the group identifier in the message's header, and classifies the message
        by its group.
      </para>
      <para>
        Message group support is specified by providing one or more of the following settings
        in the arguments map that is used when declaring the queue (e.g. when calling
        <code>AMQSession.createQueue()</code>).
          <table>
            <title>Queue Declare Message Group Configuration Arguments</title>
            <tgroup cols="2">
              <thead>
                <row>
                  <entry>Key</entry>
                  <entry>Value</entry>
                </row>
              </thead>
              <tbody>
                <row>
                  <entry>qpid.group_header_key</entry>
                  <entry>The name of the message header that holds the group identifier value.
                  The values in this header may be of any supported type (i.e. not just strings).
                  </entry>
                </row>
                <row>
                  <entry>qpid.shared_msg_group</entry>
                  <entry>Provide a value of "1" to switch on
                  <link linkend="Java-Broker-Queues-OtherTypes-BrokerRole">C++ compatibility mode</link></entry>
                </row>
              </tbody>
            </tgroup>
          </table>
      </para>
      <para>
        It is important to note that there is no need to provide the actual group
        identifer values that will be used. The broker learns these values as messages are
        received.  Also, there is no practical limit - aside from resource limitations -
        to the number of different groups that the broker can track at run time.
      </para>
    </section>
  </section>

  <section role="h2" id="Java-Broker-Queues-OtherTypes-SetLowPrefetch">
    <title>Using low pre-fetch with special queue types</title>
    <para>Qpid clients receive buffered messages in batches, sized according to the pre-fetch value.
      The current default is 500. </para>
    <para>However, if you use the default value you will probably <emphasis>not</emphasis> see
      desirable behaviour when using priority, sorted, lvq or grouped queues. Once the broker has sent a
      message to the client its delivery order is then fixed, regardless of the special behaviour of
      the queue. </para>
    <para>For example, if using a priority queue and a prefetch of 100, and 100 messages arrive with
      priority 2, the broker will send these messages to the client. If then a new message arrives
      will priority 1, the broker cannot leap frog messages of lower priority. The priority 1 will
      be delivered at the front of the next batch of messages to be sent to the client.</para>
    <para> So, you need to set the prefetch values for your client (consumer) to make this sensible.
      To do this set the Java system property <varname>max_prefetch</varname> on the client
      environment (using -D) before creating your consumer. </para>
    <para>A default for all client connections can be set via a system property: </para>
    <programlisting>
-Dmax_prefetch=1
</programlisting>
    <para> The prefetch can be also be adjusted on a per connection basis by adding a
      <varname>maxprefetch</varname> value to the <ulink url="../../Programming-In-Apache-Qpid/html/QpidJNDI.html#section-jms-connection-url">Connection URLs</ulink>
    </para>
    <programlisting>
amqp://guest:guest@client1/development?maxprefetch='1'&amp;brokerlist='tcp://localhost:5672'
</programlisting>
    <para>Setting the Qpid pre-fetch to 1 will give exact queue-type semantics as perceived by the
      client however, this brings a performance cost. You could test with a slightly higher
      pre-fetch to trade-off between throughput and exact semantics.</para>
  </section>
</section>
