예제 #1
0
  /**
   * Emits the next message from the queue as a tuple.
   *
   * <p>Serialization schemes returning null will immediately ack and then emit unanchored on the
   * {@link #ERROR_STREAM_NAME} stream for further handling by the consumer.
   *
   * <p>If no message is ready to emit, this will wait a short time ({@link #WAIT_FOR_NEXT_MESSAGE})
   * for one to arrive on the queue, to avoid a tight loop in the spout worker.
   */
  @Override
  public void nextTuple() {
    if (spoutActive && amqpConsumer != null) {
      try {
        final QueueingConsumer.Delivery delivery = amqpConsumer.nextDelivery(WAIT_FOR_NEXT_MESSAGE);

        if (delivery == null) return;
        final long deliveryTag = delivery.getEnvelope().getDeliveryTag();
        final byte[] message = delivery.getBody();

        /////////////////// new rpc
        BasicProperties props = delivery.getProperties();
        BasicProperties replyProps =
            new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();
        //////////////////////////////
        List<Object> deserializedMessage = serialisationScheme.deserialize(message);
        if (deserializedMessage != null && deserializedMessage.size() > 0) {
          // let's see what's inside the Object List (checking)
          /*System.out.println("Lenght of the list : "+ deserializedMessage.size() +"\n");
          for (int i =0; i< deserializedMessage.size(); i++){
          	Object obj=deserializedMessage.get(i);
          	System.out.println("Object value: "+  obj + "\n" );
          }*/
          ArrayList li = new ArrayList();
          li.add(deserializedMessage.get(0));
          li.add(props);
          li.add(replyProps);
          deserializedMessage = li;
          collector.emit(deserializedMessage, deliveryTag);
          /////////// new for AMQPSpout RPC+JSON
          try {
            String response = "your name was: " + deserializedMessage.get(0) + " ";
            this.amqpChannel.basicPublish(
                "", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
            // this.amqpChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            this.amqpChannel.basicAck(deliveryTag, false);
          }
          /// publishjson(props, replyProps, delivery.detEnvelope().getDeliveryTag());
          // try{
          //	publishjson(props, replyProps);
          // }
          catch (IOException e) {
            log.error("Error when publishing to the response queue", e);
          }
          ////////////////
        } else {
          handleMalformedDelivery(deliveryTag, message);
        }
      } catch (ShutdownSignalException e) {
        log.warn("AMQP connection dropped, will attempt to reconnect...");
        Utils.sleep(WAIT_AFTER_SHUTDOWN_SIGNAL);
        reconnect();
      } catch (InterruptedException e) {
        // interrupted while waiting for message, big deal
      }
    }
  }
예제 #2
0
파일: Server.java 프로젝트: robshep/rmivm
  public void run() {
    System.out.println(" [x] Awaiting RPC requests");

    while (run.get()) {

      QueueingConsumer.Delivery delivery;
      try {
        delivery = consumer.nextDelivery(2000);
      } catch (ShutdownSignalException e2) {
        break;
      } catch (ConsumerCancelledException e2) {
        break;
      } catch (InterruptedException e2) {
        continue;
      }

      BasicProperties props = delivery.getProperties();
      BasicProperties replyProps =
          new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();

      try {
        Object o;
        synchronized (registry) {
          o = Rmivm.deserialise(delivery.getBody(), registry);
        }

        byte[] outBytes = Rmivm.serialize(o);

        synchronized (channel) {
          channel.basicPublish("", props.getReplyTo(), replyProps, outBytes);
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

      } catch (Exception e) {
        try {
          synchronized (channel) {
            channel.basicPublish(
                "", props.getReplyTo(), replyProps, Rmivm.serialize(new Exception("Boom!")));
          }

        } catch (IOException e1) {
          // panic
        }
      }
    }

    System.out.println(" [x] Shutting Down");
  }
예제 #3
0
파일: Server.java 프로젝트: FFng/sourcecode
  public void serveRequests() {
    while (true) {
      try {

        Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        System.out.println("Received API call...replying...");

        channel.basicPublish("", props.getReplyTo(), null, getResponse(delivery).getBytes("UTF-8"));

      } catch (Exception e) {
        System.out.println(e.toString());
      }
    }
  }
예제 #4
0
    @Override
    public void run() {
      try {
        Connection connection = factory.newConnection();
        String uuid = UUID.randomUUID().toString();
        String queueName = RPC_QUEUE_NAME + uuid;
        Map<String, Channel> result =
            this.server.initChannel(connection, this.assignedNumber, queueName);
        Channel consumerChannel = result.get("consumer");

        Channel publisherChannel = result.get("publisher");

        QueueingConsumer consumer = new QueueingConsumer(consumerChannel);
        consumerChannel.basicConsume(queueName, true, consumer);
        System.out.println("in server ");
        while (true) {
          QueueingConsumer.Delivery delivery = consumer.nextDelivery();
          // System.out.printf("delivery is %s, body is %s", delivery, new
          // String(delivery.getBody()));
          BasicProperties props = delivery.getProperties();
          // System.out.printf("correlationId is %s", props.getCorrelationId());
          BasicProperties replyProps =
              new BasicProperties.Builder()
                  .correlationId(props.getCorrelationId())
                  .messageId(props.getMessageId())
                  .build();

          String response = new String(delivery.getBody());
          // System.out.printf("response is %s", new String(delivery.getBody()));
          // System.out.printf("reply to is %s",  props.getReplyTo()        );
          publisherChannel.basicPublish(
              PUBLISHER_EXCHANGE_NAME, props.getReplyTo(), replyProps, response.getBytes());

          // consumerChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
예제 #5
0
 @Override
 public void handleMessage(String topic, Map<String, Object> message, BasicProperties props) {
   if (props.getCorrelationId().equals(requestId)) {
     handleResponse(message, props);
   }
 }
 public MessageProperties toMessageProperties(
     final BasicProperties source, final Envelope envelope, final String charset) {
   MessageProperties target = new MessageProperties();
   Map<String, Object> headers = source.getHeaders();
   if (!CollectionUtils.isEmpty(headers)) {
     for (Map.Entry<String, Object> entry : headers.entrySet()) {
       String key = entry.getKey();
       if (MessageProperties.X_DELAY.equals(key)) {
         Object value = entry.getValue();
         if (value instanceof Integer) {
           target.setReceivedDelay((Integer) value);
         }
       } else {
         target.setHeader(key, convertLongStringIfNecessary(entry.getValue(), charset));
       }
     }
   }
   target.setTimestamp(source.getTimestamp());
   target.setMessageId(source.getMessageId());
   target.setReceivedUserId(source.getUserId());
   target.setAppId(source.getAppId());
   target.setClusterId(source.getClusterId());
   target.setType(source.getType());
   Integer deliveryMode = source.getDeliveryMode();
   if (deliveryMode != null) {
     target.setReceivedDeliveryMode(MessageDeliveryMode.fromInt(deliveryMode));
   }
   target.setDeliveryMode(null);
   target.setExpiration(source.getExpiration());
   target.setPriority(source.getPriority());
   target.setContentType(source.getContentType());
   target.setContentEncoding(source.getContentEncoding());
   String correlationId = source.getCorrelationId();
   if (StringUtils.hasText(correlationId)) {
     target.setCorrelationId(source.getCorrelationId());
   }
   String replyTo = source.getReplyTo();
   if (replyTo != null) {
     target.setReplyTo(replyTo);
   }
   if (envelope != null) {
     target.setReceivedExchange(envelope.getExchange());
     target.setReceivedRoutingKey(envelope.getRoutingKey());
     target.setRedelivered(envelope.isRedeliver());
     target.setDeliveryTag(envelope.getDeliveryTag());
   }
   return target;
 }
예제 #7
0
 public static MessageProperties valueOf(BasicProperties bp) {
   MessageProperties mp = new MessageProperties();
   mp.setAppId(bp.getAppId());
   mp.setClusterId(bp.getClusterId());
   mp.setContentEncoding(bp.getContentEncoding());
   mp.setContentType(bp.getContentType());
   mp.setCorrelationId(bp.getCorrelationId());
   mp.setDeliveryMode(bp.getDeliveryMode());
   mp.setExpiration(bp.getExpiration());
   mp.setHeaders(bp.getHeaders());
   mp.setMessageId(bp.getMessageId());
   mp.setPriority(bp.getPriority());
   mp.setReplyTo(bp.getReplyTo());
   mp.setTimestamp(bp.getTimestamp());
   mp.setType(bp.getType());
   mp.setUserId(bp.getUserId());
   return mp;
 }