Package com.rabbitmq.client

Examples of com.rabbitmq.client.Channel


    /**
     * Open channel
     */
    private Channel openChannel() throws IOException {
        log.trace("Creating channel...");
        Channel channel = conn.createChannel();
        log.debug("Created channel: {}", channel);
        // setup the basicQos
        if (endpoint.isPrefetchEnabled()) {
            channel.basicQos(endpoint.getPrefetchSize(), endpoint.getPrefetchCount(),
                    endpoint.isPrefetchGlobal());
        }
        return channel;
    }
View Full Code Here


    /**
     * Add a consumer thread for given channel
     */
    private void startConsumers() throws IOException {
        // First channel used to declare Exchange and Queue
        Channel channel = openChannel();
        if (getEndpoint().isDeclare()) {
            endpoint.declareExchangeAndQueue(channel);
        }
        startConsumer(channel);
        // Other channels
View Full Code Here

    factory.setVirtualHost(je.getFetcherQConf().getVhost());
    factory.setHost(je.getFetcherQConf().getHost());
    factory.setPort(je.getFetcherQConf().getPort());
   
    Connection conn = null;
    Channel channel = null;
   
    try {
      conn = factory.newConnection();
      channel = conn.createChannel();
      PurgeOk ok = channel.queuePurge(je.getQueue());
      _logger.info("purged queue: " +je.getQueue() + " result: " + ok.toString() + " on " + je.getFetcherQConf().getHost() + "," + je.getFetcherQConf().getVhost());
      return true;
    } catch (IOException e) {
      _logger.error(e, e);
    } finally {
      try {
        if (channel != null) channel.close();
      } catch (IOException e) {
        _logger.error(e, e);
      }
      try {
        if (conn!= null) conn.close();
View Full Code Here

    factory.setVirtualHost(this.getFetcherQConf().getVhost());
    factory.setHost(this.getFetcherQConf().getHost());
    factory.setPort(this.getFetcherQConf().getPort());
   
    Connection conn = null;
    Channel channel = null;
    try {
      conn = factory.newConnection();
      // in one thread
      channel = conn.createChannel();
      String exchangeName = getExchange();//"image_admin_exchange";
      String type = this.getType();
      String queueName = getQueue();//"image_admin";
      boolean exclusive = false;
      boolean autoDelete = false;
      boolean durable = true;
      String routingKey = "";
     
      channel.exchangeDeclare(exchangeName, type, durable);
      channel.queueDeclare(queueName, durable, exclusive, autoDelete, null);
      channel.queueBind(queueName, exchangeName, routingKey);
     
      boolean autoAck = false;
      QueueingConsumer consumer = new QueueingConsumer(channel);
      channel.basicConsume(queueName, autoAck, consumer);
     
      boolean run = true;
      while (run) {
        final ReentrantLock runLock = this.runLock;
              runLock.lock();
              try {
            QueueingConsumer.Delivery delivery;
            try {
                delivery = consumer.nextDelivery(DELIVERY_WAIT_TIMEOUT);
                if(null == delivery)
                  continue;
            } catch (InterruptedException ie) {
              _logger.error("[THREAD INTERRUPT] consumer get interrupted :" + queueName);
              run = false;
              continue;
            }
           
            byte[] bobyByte = delivery.getBody();
            String bodyStr = new String(bobyByte, this.getEncoding());//"US-ASCII", "utf-8"
           
          if(dispatchJob(this.getName(), bodyStr)) {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
           
            completedJobs.incrementAndGet();
            _logger.info("ack meg:" + delivery.getEnvelope().getDeliveryTag());
          } else {
            channel.basicReject(delivery.getEnvelope().getDeliveryTag(), true);
          }
           
            if (Bootstrap.once) run = false;
              } finally {
                  runLock.unlock();
              }
      }
    } catch (IOException e) {
      _logger.error(e, e);
    } finally {
      try {
        if (channel != null) channel.close();
      } catch (IOException e) {
        _logger.error(e, e);
      }
      try {
        if (conn!= null) conn.close();
View Full Code Here

            log.warn(cause, "Connection closed!");
          }
        }
    );

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(
        new ShutdownListener()
        {
          @Override
          public void shutdownCompleted(ShutdownSignalException cause)
          {
            log.warn(cause, "Channel closed!");
          }
        }
    );

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose()
    {
      /**
       * Storing the latest delivery as a member variable should be safe since this will only be run
       * by a single thread.
       */
      private Delivery delivery;

      /**
       * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
       * and including this tag. See commit() for more detail.
       */
      private long lastDeliveryTag;

      @Override
      public boolean hasMore()
      {
        delivery = null;
        try {
          // Wait for the next delivery. This will block until something is available.
          delivery = consumer.nextDelivery();
          if (delivery != null) {
            lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
            // If delivery is non-null, we report that there is something more to process.
            return true;
          }
        }
        catch (InterruptedException e) {
          // A little unclear on how we should handle this.

          // At any rate, we're in an unknown state now so let's log something and return false.
          log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
        }

        // This means that delivery is null or we caught the exception above so we report that we have
        // nothing more to process.
        return false;
      }

      @Override
      public InputRow nextRow()
      {
        if (delivery == null) {
          //Just making sure.
          log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
          return null;
        }

        return stringParser.parse(new String(delivery.getBody(), Charsets.UTF_8));
      }

      @Override
      public Runnable commit()
      {
        // This method will be called from the same thread that calls the other methods of
        // this Firehose. However, the returned Runnable will be called by a different thread.
        //
        // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
        // acknowledge values up to and including that value.
        return new Runnable()
        {
          // Store (copy) the last delivery tag to "become" thread safe.
          final long deliveryTag = lastDeliveryTag;

          @Override
          public void run()
          {
            try {
              log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

              // Acknowledge all messages up to and including the stored delivery tag.
              channel.basicAck(deliveryTag, true);
            }
            catch (IOException e) {
              log.error(e, "Unable to acknowledge message reception to message queue.");
            }
          }
        };
      }

      @Override
      public void close() throws IOException
      {
        log.info("Closing connection to RabbitMQ");
        channel.close();
        connection.close();
      }
    };
  }
View Full Code Here

    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do{
      int wp = (10 + r.nextInt(90)) * 100;
      String gender = r.nextBoolean() ? "male" : "female";
      int age = 20 + r.nextInt(70);

      String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

      channel.basicPublish(exchange, routingKey, null, line.getBytes());

      System.out.println("Sent message: " + line);

      timer.add(Calendar.SECOND, interval);

View Full Code Here

        }
    }

    public void testConsumeFail() throws IOException, InterruptedException {
        QueueingConsumer c = new QueueingConsumer(channel);
        Channel ch = connection.createChannel();
        try {
            ch.basicConsume(QUEUE, false, c);
        } catch (IOException e) {
            // Can't have ack mode
            checkShutdownSignal(AMQP.PRECONDITION_FAILED, e);
        }

        ch = connection.createChannel();
        ch.basicConsume(QUEUE, true, c);
        try {
            ch.basicConsume(QUEUE, true, c);
        } catch (IOException e) {
            // Can't have multiple consumers
            checkShutdownSignal(AMQP.PRECONDITION_FAILED, e);
        }
    }
View Full Code Here

    private String declareQueue(String name, Map<String, Object> args) throws IOException {
        return channel.queueDeclare(name, false, true, false, args).getQueue();
    }

    private boolean queueExists(String name) throws IOException {
        Channel ch2 = connection.createChannel();
        try {
            ch2.queueDeclarePassive(name);
            return true;
        } catch (IOException ioe) {
            return false;
        }
    }
View Full Code Here

        alternateConnection = clusteredConnection == null ? connection : clusteredConnection;
    }

    private boolean clustered(Connection c1, Connection c2) throws IOException {
        Channel ch1 = c1.createChannel();
        Channel ch2 = c2.createChannel();
        // autodelete but not exclusive
        String q = ch1.queueDeclare("", false, false, true, null).getQueue();

        try {
            ch2.queueDeclarePassive(q);
        } catch (IOException e) {
            checkShutdownSignal(AMQP.NOT_FOUND, e);
            // If we can't see the queue, secondary node must be up but not
            // clustered, hence not interesting to us
            return false;
        }

        ch1.queueDelete(q);
        ch1.close();
        ch2.close();

        return true;
    }
View Full Code Here

    public void testSelect()
        throws IOException
    {
        channel.confirmSelect();
        try {
            Channel ch = connection.createChannel();
            ch.confirmSelect();
            ch.txSelect();
            fail();
        } catch (IOException ioe) {
            checkShutdownSignal(AMQP.PRECONDITION_FAILED, ioe);
        }
        try {
            Channel ch = connection.createChannel();
            ch.txSelect();
            ch.confirmSelect();
            fail();
        } catch (IOException ioe) {
            checkShutdownSignal(AMQP.PRECONDITION_FAILED, ioe);
        }
    }
View Full Code Here

TOP

Related Classes of com.rabbitmq.client.Channel

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.