List of usage examples for com.rabbitmq.client ShutdownListener ShutdownListener
ShutdownListener
From source file:biospectra.classify.server.RabbitMQInputClient.java
License:Apache License
public synchronized void connect() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); String hostname = this.conf.getRabbitMQHostnames().get(this.hostId); factory.setHost(hostname);//from www .jav a 2s . c o m factory.setPort(this.conf.getRabbitMQPort()); factory.setUsername(this.conf.getRabbitMQUserId()); factory.setPassword(this.conf.getRabbitMQUserPwd()); factory.setRequestedHeartbeat(60); factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.shutdownListener = new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException sse) { LOG.error("connection shutdown", sse); } }; this.connection.addShutdownListener(this.shutdownListener); this.requestChannel = this.connection.createChannel(); this.responseChannel = this.connection.createChannel(); LOG.info("reader connected - " + hostname + ":" + this.conf.getRabbitMQPort()); this.responseChannel.basicQos(10); this.queueName = this.responseChannel.queueDeclare().getQueue(); this.consumer = new DefaultConsumer(this.responseChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); this.getChannel().basicAck(envelope.getDeliveryTag(), false); LOG.info("> " + message); ClassificationResponseMessage res = ClassificationResponseMessage.createInstance(message); ClassificationRequest ereq = null; synchronized (requestMap) { ereq = requestMap.get(res.getReqId()); if (ereq != null) { requestMap.remove(res.getReqId()); } } if (ereq == null) { LOG.error("cannot find matching request"); } else { ClassificationResponse eres = new ClassificationResponse(ereq, res); boolean responded = false; synchronized (ereq) { ClassificationRequest.RequestStatus status = ereq.getStatus(); if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) { ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_RESPONDED); responded = true; } requestQueue.remove(ereq); } if (responded) { LOG.info("res : " + ereq.getReqId()); if (handler != null) { handler.onSuccess(eres.getReqId(), eres.getHeader(), eres.getSequence(), eres.getResult(), eres.getType(), eres.getTaxonRank(), eres.getTaxonName()); } synchronized (requestQueue) { requestQueue.notifyAll(); } } } } }; this.workerThread = new Thread(new Runnable() { @Override public void run() { try { responseChannel.basicConsume(queueName, consumer); LOG.info("Waiting for messages"); } catch (IOException ex) { LOG.error("Exception occurred while consuming a message", ex); } } }); this.workerThread.start(); this.reachable = true; this.timeoutThread = new Thread(new Runnable() { @Override public void run() { while (true) { boolean cont = false; if (requestQueue.size() > 0) { ClassificationRequest ereq = requestQueue.peek(); Date cur = new Date(); if (ereq != null && cur.getTime() - ereq.getSentTime() >= QUERY_TIMEOUT) { LOG.info("found timeout request"); //timeout boolean timeout = false; synchronized (ereq) { ClassificationRequest.RequestStatus status = ereq.getStatus(); if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) { ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_TIMEOUT); timeout = true; } requestQueue.remove(ereq); } synchronized (requestMap) { requestMap.remove(ereq.getReqId()); } if (timeout) { LOG.info("timeout : " + ereq.getReqId()); handler.onTimeout(ereq.getReqId(), ereq.getHeader(), ereq.getSequence()); synchronized (requestQueue) { requestQueue.notifyAll(); } } cont = true; } } if (!cont) { try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } } } } }); this.timeoutThread.start(); }
From source file:biospectra.classify.server.RabbitMQInputServer.java
License:Apache License
public synchronized void connect() throws IOException, TimeoutException { LOG.info("Connecting to - " + this.conf.getRabbitMQHostname() + ":" + this.conf.getRabbitMQPort()); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.conf.getRabbitMQHostname()); factory.setPort(this.conf.getRabbitMQPort()); factory.setUsername(this.conf.getRabbitMQUserId()); factory.setPassword(this.conf.getRabbitMQUserPwd()); factory.setRequestedHeartbeat(60);//from ww w . j a v a 2 s . com factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException sse) { LOG.error("connection shutdown", sse); } }); this.requestChannel = this.connection.createChannel(); this.responseChannel = this.connection.createChannel(); LOG.info("connected."); this.requestChannel.basicQos(1); this.requestChannel.queueDeclare("request", false, false, true, null); this.responseChannel.addReturnListener(new ReturnListener() { @Override public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); LOG.info("message not delivered to " + routingKey); LOG.info(message); } }); this.consumer = new DefaultConsumer(this.requestChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); this.getChannel().basicAck(envelope.getDeliveryTag(), false); if (handler != null) { ClassificationRequestMessage req = ClassificationRequestMessage.createInstance(message); handler.handleMessage(req, properties.getReplyTo()); } } }; this.workerThread = new Thread(new Runnable() { @Override public void run() { try { requestChannel.basicConsume("request", consumer); LOG.info("Waiting for messages"); } catch (IOException ex) { LOG.error("Exception occurred while consuming a message", ex); } } }); this.workerThread.start(); }
From source file:com.cisco.oss.foundation.message.ChannelWrapper.java
License:Apache License
static void connect() { try {// ww w . jav a 2s . c o m Configuration configuration = ConfigurationFactory.getConfiguration(); final Map<String, Map<String, String>> serverConnections = ConfigUtil .parseComplexArrayStructure("service.rabbitmq.connections"); final ArrayList<String> serverConnectionKeys = Lists.newArrayList(serverConnections.keySet()); Collections.sort(serverConnectionKeys); int maxRetryAttempts = configuration.getInt("service.rabbitmq.maxRetryAttempts", 1000); Config config = new Config() .withRecoveryPolicy(new RecoveryPolicy().withBackoff(Duration.seconds(1), Duration.seconds(30)) .withMaxAttempts(maxRetryAttempts)) .withConnectionRecoveryPolicy( new RecoveryPolicy().withBackoff(Duration.seconds(1), Duration.seconds(30)) .withMaxAttempts(maxRetryAttempts)) .withConsumerRecovery(true).withExchangeRecovery(true).withQueueRecovery(true) .withConnectionListeners(new ConnectionListener() { @Override public void onCreate(Connection connection) { LOGGER.trace("connection create: {}", connection); } @Override public void onCreateFailure(Throwable failure) { LOGGER.error("connection create failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecoveryStarted(Connection connection) { LOGGER.trace("connection recovery started: {}", connection); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecovery(Connection connection) { LOGGER.trace("connection recovered: {}", connection); } @Override public void onRecoveryCompleted(Connection connection) { LOGGER.trace("connection recovery completed: {}", connection); IS_CONNECCTION_OR_CHANNEL_UP.set(true); } @Override public void onRecoveryFailure(Connection connection, Throwable failure) { LOGGER.error("connection recovery failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } }).withChannelListeners(new ChannelListener() { @Override public void onCreate(Channel channel) { LOGGER.trace("channel create: {}", channel); } @Override public void onCreateFailure(Throwable failure) { LOGGER.error("channel create failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecoveryStarted(Channel channel) { LOGGER.trace("channel recovery started: {}", channel); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecovery(Channel channel) { LOGGER.trace("channel recovered: {}", channel); } @Override public void onRecoveryCompleted(Channel channel) { LOGGER.trace("channel recovery completed: {}", channel); IS_CONNECCTION_OR_CHANNEL_UP.set(true); } @Override public void onRecoveryFailure(Channel channel, Throwable failure) { LOGGER.error("channel recovery failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } }).withConsumerListeners(new ConsumerListener() { @Override public void onRecoveryStarted(Consumer consumer, Channel channel) { LOGGER.trace("consumer create. consumer: {}, channel: {}", consumer, channel); IS_CONSUMER_UP.set(false); } @Override public void onRecoveryCompleted(Consumer consumer, Channel channel) { LOGGER.trace("consumer recovery completed: {}, channel: {}", consumer, channel); IS_CONSUMER_UP.set(true); } @Override public void onRecoveryFailure(Consumer consumer, Channel channel, Throwable failure) { LOGGER.error("consumer recovery failed. consumer: {}, channel: {}, error: {}", consumer, channel, failure.toString(), failure); IS_CONSUMER_UP.set(false); } }); config.getRecoverableExceptions().add(UnknownHostException.class); config.getRecoverableExceptions().add(NoRouteToHostException.class); List<Address> addresses = new ArrayList<>(5); for (String serverConnectionKey : serverConnectionKeys) { Map<String, String> serverConnection = serverConnections.get(serverConnectionKey); String host = serverConnection.get("host"); int port = Integer.parseInt(serverConnection.get("port")); addresses.add(new Address(host, port)); } Address[] addrs = new Address[0]; ConnectionOptions options = new ConnectionOptions().withAddresses(addresses.toArray(addrs)); final ConnectionFactory connectionFactory = options.getConnectionFactory(); connectionFactory.setAutomaticRecoveryEnabled(false); connectionFactory.setTopologyRecoveryEnabled(false); final boolean metricsAndMonitoringIsEnabled = configuration .getBoolean("service.rabbitmq.metricsAndMonitoringJmx.isEnabled", false); if (metricsAndMonitoringIsEnabled) { MetricRegistry registry = new MetricRegistry(); StandardMetricsCollector metrics = new StandardMetricsCollector(registry); connectionFactory.setMetricsCollector(metrics); JmxReporter reporter = JmxReporter.forRegistry(registry).inDomain("com.rabbitmq.client.jmx") .build(); reporter.start(); } final boolean useNio = configuration.getBoolean("service.rabbitmq.useNio", false); if (useNio) { NioParams nioParams = new NioParams(); final Integer nbIoThreads = configuration.getInteger("service.rabbitmq.nio.nbIoThreads", null); final Integer readByteBufferSize = configuration .getInteger("service.rabbitmq.nio.readByteBufferSize", null); final Integer writeByteBufferSize = configuration .getInteger("service.rabbitmq.nio.writeByteBufferSize", null); final Integer writeEnqueuingTimeoutInMs = configuration .getInteger("service.rabbitmq.nio.writeEnqueuingTimeoutInMs", null); final Integer writeQueueCapacity = configuration .getInteger("service.rabbitmq.nio.writeQueueCapacity", null); if (nbIoThreads != null) { nioParams.setNbIoThreads(nbIoThreads); } if (readByteBufferSize != null) { nioParams.setReadByteBufferSize(readByteBufferSize); } if (writeByteBufferSize != null) { nioParams.setWriteByteBufferSize(writeByteBufferSize); } if (writeEnqueuingTimeoutInMs != null) { nioParams.setWriteEnqueuingTimeoutInMs(writeEnqueuingTimeoutInMs); } if (writeQueueCapacity != null) { nioParams.setWriteQueueCapacity(writeQueueCapacity); } // nioParams.setNioExecutor() // nioParams.setThreadFactory() options.withNio().withNioParams(nioParams); } Configuration subsetBase = configuration.subset("service.rabbitmq"); Configuration subsetSecurity = subsetBase.subset("security"); int requestHeartbeat = subsetBase.getInt("requestHeartbeat", 10); options.withRequestedHeartbeat(Duration.seconds(requestHeartbeat)); String userName = subsetSecurity.getString("userName"); String password = subsetSecurity.getString("password"); boolean isEnabled = subsetSecurity.getBoolean("isEnabled"); if (isEnabled) { options.withUsername(userName).withPassword(password); } connection = Connections.create(options, config); connection.addBlockedListener(new BlockedListener() { public void handleBlocked(String reason) throws IOException { LOGGER.error("RabbitMQ connection is now blocked. Port: {}, Reason: {}", connection.getPort(), reason); IS_BLOCKED.set(true); } public void handleUnblocked() throws IOException { LOGGER.info("RabbitMQ connection is now un-blocked. Port: {}", connection.getPort()); IS_BLOCKED.set(false); } }); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { LOGGER.error("Connection shutdown detected. Reason: {}", cause.toString(), cause); IS_CONNECTED.set(false); } }); IS_CONNECTED.set(true); IS_CONNECCTION_OR_CHANNEL_UP.set(true); IS_CONSUMER_UP.set(true); INIT_LATCH.countDown(); } catch (Exception e) { LOGGER.error("can't create RabbitMQ Connection: {}", e, e); // triggerReconnectThread(); throw new QueueException(e); } }
From source file:com.ericsson.eiffel.remrem.publish.helper.RabbitMqProperties.java
License:Apache License
/** * This method is used to publish the message to RabbitMQ * @param routingKey// w w w. j av a 2 s . com * @param msg is Eiffel Event * @throws IOException */ public void send(String routingKey, String msg) throws IOException { Channel channel = giveMeRandomChannel(); channel.addShutdownListener(new ShutdownListener() { public void shutdownCompleted(ShutdownSignalException cause) { // Beware that proper synchronization is needed here if (cause.isInitiatedByApplication()) { log.debug("Shutdown is initiated by application. Ignoring it."); } else { log.error("Shutdown is NOT initiated by application."); log.error(cause.getMessage()); boolean cliMode = Boolean.getBoolean(PropertiesConfig.CLI_MODE); if (cliMode) { System.exit(-3); } } } }); BasicProperties msgProps = MessageProperties.BASIC; if (usePersitance) msgProps = MessageProperties.PERSISTENT_BASIC; channel.basicPublish(exchangeName, routingKey, msgProps, msg.getBytes()); log.info("Published message with size {} bytes on exchange '{}' with routing key '{}'", msg.getBytes().length, exchangeName, routingKey); }
From source file:com.esri.geoevent.transport.rabbitmq.RabbitMQComponentBase.java
License:Apache License
protected synchronized void init() throws RabbitMQTransportException { try {// ww w. j av a 2 s . c om channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { disconnect(cause.getMessage()); } }); channel.exchangeDeclare(exchange.getName(), exchange.getType().toString(), exchange.isDurable(), exchange.isAutoDelete(), null); } catch (IOException e) { String msg = LOGGER.translate("EXCHANGE_CREATE_ERROR", e.getMessage()); LOGGER.error(msg, e); throw new RabbitMQTransportException(msg); } }
From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java
/** * @param args the command line arguments * @throws java.lang.Exception/*from w w w . j a v a 2 s. co m*/ */ public static void main(String[] args) throws Exception { /** * Set properties at runtime */ System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log"); AppConstants.loadAppConfig(); final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getDlrReceiverExchangeName(); final String routingKey = GATEWAY_ID; Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class); try { Connection connection = AppConstants.getRabbitMqObject().newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { //throw new UnsupportedOperationException("Not supported yet."); if (cause.isHardError()) { Connection conn; conn = (Connection) cause.getReference(); if (!cause.isInitiatedByApplication()) { Method reason = cause.getReason(); logger.info("REASON:" + reason.toString()); } } else { Channel ch = (Channel) cause.getReference(); logger.info("NO HARDSHUTDOWN"); } } }); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); channel.basicQos(1000); //channel.addShutdownListener(listener); logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C"); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Map<String, String> dataToPost = new HashMap<>(); String payload = new String(body, "UTF-8"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); //check if any parameter is empty if (s.length == 2) { dataToPost.put(s[0], s[1]); } else { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]); dataToPost.put(s[0], null); } } long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); dataToPost.clear(); payloadParts = null; } }; String cTag = channel.basicConsume(queueName, false, consumer); logger.info("CONSUMER TAG : " + cTag); } catch (IOException | TimeoutException e) { logger.error("RMQ_ERROR:" + e.getMessage()); } }
From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java
/** * @param args the command line arguments * @throws java.lang.Exception/*w w w .ja v a2 s . co m*/ */ public static void main(String[] args) throws Exception { /** * Set properties at runtime */ System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log"); AppConstants.loadAppConfig(); final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getSmsReceiverExchangeName(); final String routingKey = GATEWAY_ID; Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class); try { Connection connection = AppConstants.getRabbitMqObject().newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { //throw new UnsupportedOperationException("Not supported yet."); if (cause.isHardError()) { Connection conn; conn = (Connection) cause.getReference(); if (!cause.isInitiatedByApplication()) { Method reason = cause.getReason(); logger.info("REASON:" + reason.toString()); } } else { Channel ch = (Channel) cause.getReference(); logger.info("NO HARDSHUTDOWN"); } } }); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); channel.basicQos(1000); //channel.addShutdownListener(listener); logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C"); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Map<String, String> dataToPost = new HashMap<>(); String payload = new String(body, "UTF-8"); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); dataToPost.put(s[0], s[1]); } logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload); long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { if (saveRequestData()) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); API_CALL_STATS.clear(); dataToPost.clear(); payloadParts = null; } }; String cTag = channel.basicConsume(queueName, false, consumer); logger.info("CONSUMER TAG : " + cTag); } catch (IOException | TimeoutException e) { logger.error("RMQ_ERROR:" + e.getMessage()); } }
From source file:com.shopwiki.roger.RabbitConnector.java
License:Apache License
private Connection _getConnection(int numThreads) throws IOException { ConnectionFactory connFactory = new ConnectionFactory(); ThreadFactory threadFactory = DaemonThreadFactory.getInstance("RabbitMQ-ConsumerThread", true); final ExecutorService executor = Executors.newFixedThreadPool(numThreads, threadFactory); Address[] array = addresses.toArray(new Address[0]); Connection conn = connFactory.newConnection(executor, array); conn.addShutdownListener(new ShutdownListener() { @Override//from www . java2 s. c o m public void shutdownCompleted(ShutdownSignalException sse) { executor.shutdown(); } }); return conn; }
From source file:com.sitewhere.sources.rabbitmq.RabbitMqInboundEventReceiver.java
License:Open Source License
private void connect() { try {/* w w w . jav a2s .c o m*/ this.connection = factory.newConnection(executors); connection.addShutdownListener(new ShutdownListener() { public void shutdownCompleted(ShutdownSignalException cause) { LOGGER.info("shutdown signal received", cause); // Do nothing if SiteWhere initiated the connection close if (!cause.isInitiatedByApplication()) { connection = null; scheduleReconnect(); } } }); this.channel = connection.createChannel(); LOGGER.info("RabbitMQ receiver connected to: " + getConnectionUri()); channel.queueDeclare(getQueueName(), isDurable(), false, false, null); LOGGER.info("RabbitMQ receiver using " + (isDurable() ? "durable " : "") + "queue: " + getQueueName()); // Add consumer callback for channel. Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { onEventPayloadReceived(body, null); } }; channel.basicConsume(getQueueName(), true, consumer); } catch (Exception e) { LOGGER.error("Connection Error", e); connection = null; scheduleReconnect(); } }
From source file:com.vmware.vhadoop.vhm.rabbit.RabbitConnection.java
License:Open Source License
private Connection getConnection() throws IOException { synchronized (_connectionLock) { if (_connection == null || !_connection.isOpen()) { _connection = null;/*from w w w .j ava 2s . c o m*/ _connection = _connectionFactory.newConnection(); _connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { _log.info("Connection shut down"); _log.log(Level.FINE, "{0}", cause.getReason()); synchronized (_connectionLock) { _connection = null; _channel = null; _queueName = null; } _started = false; } }); _started = true; _log.fine("Created new connection"); } return _connection; } }