📄 consumermanager.java
字号:
/**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 2001-2003 (C) Exoffice Technologies Inc. All Rights Reserved.
*
* $Id: ConsumerManager.java,v 1.33 2003/09/25 11:24:16 tanderson Exp $
*
* Date Author Changes * 3/1/2001 jima Created
*/
package org.exolab.jms.messagemgr;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;
import javax.jms.DeliveryMode;
import javax.jms.InvalidSelectorException;
import javax.jms.JMSException;
import javax.transaction.TransactionManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.exolab.core.service.ServiceException;
import org.exolab.jms.client.JmsDestination;
import org.exolab.jms.client.JmsQueue;
import org.exolab.jms.client.JmsTopic;
import org.exolab.jms.gc.GarbageCollectable;
import org.exolab.jms.gc.GarbageCollectionService;
import org.exolab.jms.message.MessageImpl;
import org.exolab.jms.persistence.DatabaseService;
import org.exolab.jms.persistence.PersistenceAdapter;
import org.exolab.jms.persistence.PersistenceException;
import org.exolab.jms.persistence.SQLHelper;
import org.exolab.jms.scheduler.Scheduler;
import org.exolab.jms.server.JmsServerSession;
/**
* The consumer manager is responsible for creating and managing the
* lifecycle of Consumer. The consumer manager maintains a list of all
* active consumers.
* <p>
* The consumer manager, in an attempt to make better utilization of
* resource will also act as a proxy for all inactive durable subscribers
* So it will act as a DestinationCacheEventListener and process the
* message on behalf of the inactive consumer.
*
* @version $Revision: 1.33 $ $Date: 2003/09/25 11:24:16 $
* @author <a href="mailto:jima@exoffice.com">Jim Alateras</a>
*/
public class ConsumerManager
implements DestinationCacheEventListener, GarbageCollectable {
/**
* Maintains a cache of all active endpoints.
*/
private HashMap _endpoints = new HashMap();
/**
* Maintains a list of all unique consumers, durable and non-durable.
* Each entry has an associated {@link #ConsumerEntry} record. All
* durable subscribers are maintained in memory until they are removed
* from the system entirely. All non-durable subscribers are maintained
* in memory until their endpoint is removed.
*/
private HashMap _consumerCache = new HashMap();
/**
* Maintais a mapping between destinations and consumers. A destination
* can have more than one consumer and a consumer can also be registered
* to more than one destination
*/
private HashMap _destToConsumerMap = new HashMap();
/**
* Maintains a list of wildcard subscriptions using subscription name
* and the JmsTopic.
*/
private HashMap _wildcardConsumers = new HashMap();
/**
* Cache a copy of the scheduler instance
*/
private Scheduler _scheduler = null;
/**
* The singleton instance of the consumer manager
*/
private static ConsumerManager _instance = null;
/**
* The logger
*/
private static final Log _log = LogFactory.getLog(ConsumerManager.class);
/**
* Create the singleton instance of the consumer manager
*
* @return the singleton instance
* @throws ServiceException if the service cannot be initialised
*/
public static ConsumerManager createInstance() throws ServiceException {
_instance = new ConsumerManager();
return _instance;
}
/**
* Return the singleton instance of the ConsumerManager
*
* @return ConsumerManager
*/
public static ConsumerManager instance() {
return _instance;
}
/**
* Construct the <code>ConsumerManager</code>
*
* @throws ServiceException - if it fails to initialise
*/
private ConsumerManager() throws ServiceException {
// register with the GarbageCollectionService
GarbageCollectionService.instance().register(this);
init();
}
/**
* This method creates an actual durable consumer for the specified and
* caches it. It does not create and endpoint. To create the endpoint the
* client should call createDurableConsumerEndpoint.
*
* @param topic - the topic destination
* @param name - the consumer name
* @exception JMSException - if it cannot be created
*/
public synchronized void createDurableConsumer(JmsTopic topic, String name)
throws JMSException {
PersistenceAdapter adapter = DatabaseService.getAdapter();
Connection connection = null;
try {
connection = DatabaseService.getConnection();
// ensure that we are trying to create a durable consumer to an
// administered destination.
if (!adapter.checkDestination(connection, topic.getName())) {
throw new JMSException(
"Cannot create durable consumer, name=" + name +
", for non-administered topic=" + topic.getName());
}
if (!adapter.durableConsumerExists(connection, name)) {
adapter.addDurableConsumer(connection, topic.getName(), name);
}
connection.commit();
// cache the consumer locally
addToConsumerCache(name, topic, true);
} catch (JMSException exception) {
throw exception;
} catch (Exception exception) { // PersistenceException, SQLException
SQLHelper.rollback(connection);
String msg = "Failed to create durable consumer, name=" + name
+ ", for topic=" + topic.getName();
_log.error(msg, exception);
throw new JMSException(msg + ": " + exception.getMessage());
} finally {
SQLHelper.close(connection);
}
}
/**
* This method will remove the durable consumer from the database and
* from transient memory only if it exists and is inactive. If there
* is an active endpoint then it cannot be deleted and an exception
* will be raise.
* <p>
* If the durable consumer does not exist then an exception is also
* raised.
*
* @param name - the consumer name
* @exception JMSException - if it cannot be removed
*/
public synchronized void removeDurableConsumer(String name)
throws JMSException {
if (_log.isDebugEnabled()) {
_log.debug("removeDurableConsumer(name=" + name + ")");
}
// check to see that the durable consumer exists
if (!durableConsumerExists(name)) {
throw new JMSException("Durable consumer " + name +
" is not defined.");
}
if (isDurableConsumerActive(name)) {
throw new JMSException(
"Cannot remove durable consumer=" + name
+ ": consumer is active");
}
// remove it from the persistent store.
Connection connection = null;
try {
connection = DatabaseService.getConnection();
DatabaseService.getAdapter().removeDurableConsumer(connection,
name);
// if it has been successfully removed from persistent store then
// clear up the transient references.
ConsumerEndpoint endpoint = getConsumerEndpoint(name);
if (endpoint != null) {
deleteConsumerEndpoint(endpoint);
}
removeFromConsumerCache(name);
connection.commit();
} catch (Exception exception) { // PersistenceException, SQLException
SQLHelper.rollback(connection);
String msg = "Failed to remove durable consumer, name=" + name;
_log.error(msg, exception);
throw new JMSException(msg + ":" + exception.getMessage());
} finally {
SQLHelper.close(connection);
}
}
/**
* This method will remove all the durable consumers from the database and
* from transient memory whether they are active or not.
* <p>
* If we have problems removing the durable consumers then throw the
* JMSException.
*
* @param topic the topic to remove consumers for
* @throw JMSException if the consumers cannot be removed
*/
public synchronized void removeDurableConsumers(JmsDestination topic)
throws JMSException {
Vector consumers = (Vector) _destToConsumerMap.get(topic);
if (consumers != null) {
Enumeration entries = consumers.elements();
while (entries.hasMoreElements()) {
ConsumerEntry entry = (ConsumerEntry) entries.nextElement();
if (entry._durable) {
// remove the actual durable consumer from transient and
// secondary memory.
removeDurableConsumer(entry._name);
}
}
}
// remove all consumers for the specified destination
removeFromConsumerCache(topic);
}
/**
* Create a transient consumer for the specified destination. The client
* can optionally specify a selector to filter messages.
* <p>
* The clientId parameter is used to indirectly reference the remote client
* which is uniquely identifiable within a session and is used during
* asynchronous message delivery.
*
* @param clientId - indirect reference to the remote client
* @param destination - consumer for this destination
* @param selector - the consumer's selector if specified.
* @return transient consumer
*/
public synchronized ConsumerEndpoint createConsumerEndpoint(
JmsServerSession session, long clientId, JmsDestination destination,
String selector)
throws JMSException, InvalidSelectorException {
if (_log.isDebugEnabled()) {
_log.debug("createConsumerEndpoint(session=[sessionId="
+ session.getSessionId() + "], clientId=" + clientId
+ ", destination=" + destination
+ ", selector=" + selector + ")");
}
ConsumerEndpoint endpoint = null;
DestinationManager destmgr = DestinationManager.instance();
// before we create the destination we need to check the
// characteristics of the destination. If the destination
// is an administered destination then it must be already
// defined. If the destination is a temporary destination
// then we may need to add it to the cache.
if (destination.getPersistent()) {
if (!destmgr.destinationExists(destination)) {
throw new JMSException("Cannot create consumer endpoint: "
+ "destination=" + destination
+ " does not exist");
}
} else {
if (!destmgr.destinationExists(destination)) {
destmgr.createDestination(destination);
}
}
// determine what type of consumer endpoint to create based on
// the destination it subscribes too.
if (destination instanceof JmsTopic) {
JmsTopic topic = (JmsTopic) destination;
endpoint = new TopicConsumerEndpoint(session, clientId, topic,
selector, _scheduler);
} else if (destination instanceof JmsQueue) {
// this seems like a good opportunity to clean up any unreferenced
// endpoints attached to this queue.
cleanUnreferencedEndpoints(destination);
// now we can create the endpoint
endpoint = new QueueConsumerEndpoint(session, clientId,
(JmsQueue) destination, selector, _scheduler);
}
if (endpoint != null) {
// add it to the list on managed consumers
String id = endpoint.getPersistentId();
_endpoints.put(id, endpoint);
addToConsumerCache(id, destination, false);
}
return endpoint;
}
/**
* Create a durable consumer with the specified well-known name.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -