Package com.rabbitmq.client

Examples of com.rabbitmq.client.Connection


    factory.setPassword(je.getFetcherQConf().getPassword());
    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();
      } catch (IOException e) {
        _logger.error(e, e);
      }
    }
    return false;
View Full Code Here


    factory.setPassword(this.getFetcherQConf().getPassword());
    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();
      } catch (IOException e) {
        _logger.error(e, e);
      }
    }
   
View Full Code Here

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = Connections.create(lyraOptions, lyraConfig);

    connection.addShutdownListener(
        new ShutdownListener()
        {
          @Override
          public void shutdownCompleted(ShutdownSignalException cause)
          {
            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

    Calendar timer = Calendar.getInstance();
    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);

      Thread.sleep(delay);
    }while((!single && stop.after(timer.getTime())));

    connection.close();
  }
View Full Code Here

    }

    public void connectionCloseAuthFailure(String username, String password) throws IOException {
        String failDetail =  "for username " + username + " and password " + password;
        try {
            Connection conn = connectionWithoutCapabilities(username, password);
            fail("Expected PossibleAuthenticationFailureException " + failDetail);
            conn.abort();
        } catch (PossibleAuthenticationFailureException paf) {
            if (paf instanceof AuthenticationFailureException) {
                fail("Not expecting AuthenticationFailureException " + failDetail);
            }
        }
View Full Code Here

    }

    private void loginOk(String name, byte[][] responses) throws IOException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setSaslConfig(new Config(name, responses));
        Connection connection = factory.newConnection();
        connection.close();
    }
View Full Code Here

    public void onReconnection(final HaConnectionProxy connectionProxy) {

        // use a separate connection and channel to avoid race conditions with any operations that are blocked
        // waiting for the reconnection to finish...and don't cache anything otherwise you get the same problem!
        try {
            Connection connection = connectionFactory.newConnection(new Address[] { new Address(host) });
            Channel channel = connection.createChannel();

            channel.queueDeclare("testQueue", false, false, false, new HashMap<String, Object>());
            channel.queueBind("testQueue", "amq.topic", "#");

            channel.close();
            connection.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
View Full Code Here

                latch.countDown();
            }
        };
        ConnectionFactory cf = newConnectionFactory(eh);
        assertEquals(cf.getExceptionHandler(), eh);
        Connection conn = cf.newConnection();
        assertEquals(conn.getExceptionHandler(), eh);
        Channel ch = conn.createChannel();
        String q = ch.queueDeclare().getQueue();
        ch.basicConsume(q, new DefaultConsumer(ch) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                throw new RuntimeException("oops");
View Full Code Here

            //  Connect to the AMQP broker
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(hostName);
            factory.setPort(portNumber);
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            for (;;) {

                //  Send a message.
                channel.basicPublish("PIPELINE", null, null,
View Full Code Here

            //  Connect to the AMQP broker
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(hostName);
            factory.setPort(portNumber);
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            //  Establish the REQ/REP wiring.
            String queueName = channel.queueDeclare().getQueue();
            QueueingConsumer consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);

            //  Send the request
            AMQP.BasicProperties properties = new AMQP.BasicProperties();
            properties.setReplyTo(queueName);
            channel.basicPublish("", "REQREP", properties,
                "Hello!".getBytes());

            //  Get and print the reply
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String reply = new String(delivery.getBody());
            System.out.println(reply);

            connection.close();

        } catch (Exception e) {
            System.err.println("Main thread caught exception: " + e);
            e.printStackTrace();
            System.exit(1);
View Full Code Here

TOP

Related Classes of com.rabbitmq.client.Connection

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.