List of usage examples for com.rabbitmq.client BasicProperties getReplyTo
public abstract String getReplyTo();
From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpoint.java
License:Apache License
/** * Sets up a consumer that passes received messages to the * {@link MessageEndpointListener}s./*w ww . j a v a 2s . com*/ */ private void setUpConsumer() throws IOException { DefaultConsumer consumer = new DefaultConsumer(this.channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); super.getChannel().basicAck(deliveryTag, false); if (!properties.getAppId().equals(AMQPEndpoint.this.uuid.toString())) { MessageManifest mm = MessageFactory.decode(body); try { URI responseURI = new URIBuilder().routingKey(properties.getReplyTo()) .instanceName(getName()).build(); mm.setResponseURI(responseURI); } catch (URISyntaxException e) { // this should never happen! LOG.warn("Unable to create response URI for incoming message", e); } notifyMessageEndpointListeners(mm); } } }; if (this.listenForTasks) { String queueName = QUEUE_NAME_TASKS + this.routingKey; this.channel.basicConsume(queueName, false, consumer); } this.channel.basicConsume(this.exclusiveQueueName, false, consumer); // listening to the remote shutdown ShutdownListener shutdownListener = new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { shutdown(); } }; this.channel.addShutdownListener(shutdownListener); // if (this.channel.isOpen()) { // handler.handleConnectionEvent(true); // } }
From source file:dfki.sb.rabbitmqjava.RabbitMQObjectStreamServer.java
License:Open Source License
private static void processSendAndRecivePackets(QueueingConsumer consumer, Channel channel) throws InterruptedException, IOException { while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build();/*w ww.ja va2s . c om*/ try { byte[] body = delivery.getBody(); if (body.length == 0) { break; } else { Object obj = SerializationUtils.deserialize(body); if (obj instanceof MarketData) { MarketData response = sendMarketData((MarketData) obj); channel.basicPublish("", props.getReplyTo(), replyProps, SerializationUtils.serialize(response)); } else { QuoteRequest response = sendQuoteRequest((QuoteRequest) obj); channel.basicPublish("", props.getReplyTo(), replyProps, SerializationUtils.serialize(response)); } } } catch (IOException e) { System.out.println(" [.] " + e.toString()); } finally { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } }
From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java
License:Open Source License
public static void main(String[] argv) { Connection connection = null; Channel channel = null;/*from ww w .j a v a 2 s . c om*/ try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); System.out.println("Starting server waiting for client requests:"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); DataInputStream dis = new DataInputStream( new BufferedInputStream(new ByteArrayInputStream(delivery.getBody()))); try { int type = dis.readInt(); byte[] response; if (type == 2) { response = handleMarketRequest(dis); } else { response = handleQuoteRequest(dis); } channel.basicPublish("", props.getReplyTo(), replyProps, response); dis.close(); } catch (IOException | ClassNotFoundException e) { System.out.println(" [.] " + e.toString()); } finally { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (IOException ignore) { } } } }
From source file:dk.bankjsonrabbit.messaging.Send.java
public static void sendMessage(String message, BasicProperties props) throws IOException, TimeoutException { String taskQueueName = props.getReplyTo(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("student"); factory.setPassword("cph"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(taskQueueName, true, false, false, null); channel.basicPublish("", taskQueueName, props, message.getBytes()); channel.close();/*from w w w . j a va2 s . co m*/ connection.close(); }
From source file:es.devcircus.rabbitmq_examples.rabbitmq_rpc.RPCServer.java
License:Open Source License
/** * * @param argv/*www . ja v a 2 s . c om*/ */ public static void main(String[] argv) { Connection connection = null; Channel channel = null; try { ConnectionFactory factory = new ConnectionFactory(); // factory.setHost("localhost"); factory.setHost("192.168.0.202"); // factory.setPort(5671); // factory.useSslProtocol(); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); System.out.println(" [x] Awaiting RPC requests"); while (true) { String response = null; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); try { String message = new String(delivery.getBody(), "UTF-8"); int n = Integer.parseInt(message); System.out.println(" [.] fib(" + message + ")"); response = "" + fib(n); } catch (Exception e) { System.out.println(" [.] " + e.toString()); response = ""; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { System.out.println(e.toString()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:gash.router.server.MessageServer.java
License:Apache License
public void createQueue() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException, SQLException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("inbound_queue", false, false, false, null); channel.basicQos(1);/*from w w w .j a v a2 s . c om*/ postgre = new PostgreSQL(url, username, password, dbname, ssl); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("inbound_queue", false, consumer); // Map<String, byte[]> map = new HashMap<String, byte[]>(); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); String request = props.getType(); System.out.println(request); if (request != null) { if (request.equals("get")) { String key = new String(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); byte[] image = postgre.get(key); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("put")) { byte[] image = delivery.getBody(); postgre.put(props.getUserId(), image); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("post")) { System.out.println("Message Server"); String key = postgre.post(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, key.getBytes()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("delete")) { String key = new String(delivery.getBody()); postgre.delete(key); } } } }
From source file:in.cs654.chariot.ashva.AshvaServer.java
License:Open Source License
public static void main(String[] args) { Connection connection = null; Channel channel;/*from w ww. jav a 2 s . c o m*/ try { final ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST_IP_ADDR); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); LOGGER.info("Ashva Server started. Waiting for requests..."); AshvaHelper.joinOrStartChariotPool(); AshvaHelper.startHeartbeat(); while (true) { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicResponse response = new BasicResponse(); BasicRequest request = new BasicRequest(); final BasicProperties props = delivery.getProperties(); final BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); try { final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>( BasicRequest.class); decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder); request = avroReader.read(request, decoder); response = AshvaProcessor.process(request); } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in handling request: " + e.getMessage()); response = ResponseFactory.getErrorResponse(request); } finally { baos.reset(); final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>( BasicResponse.class); encoder = EncoderFactory.get().binaryEncoder(baos, encoder); avroWriter.write(response, encoder); encoder.flush(); LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus()); channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in RPC server: " + e.getMessage()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:in.cs654.chariot.prashti.PrashtiServer.java
License:Open Source License
public static void main(String[] args) { Connection connection = null; Channel channel;/*from www .ja v a2s. co m*/ try { final ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST_IP_ADDR); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); LOGGER.info("Prashti Server started. Waiting for requests..."); final List<Prashti> prashtiList = D2Client.getOnlinePrashtiServers(); final String ipAddr = CommonUtils.getIPAddress(); prashtiList.add(new Prashti(ipAddr)); LOGGER.info("Notifying D2 to set Prashti Server IP Address"); D2Client.setPrashtiServers(prashtiList); while (true) { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicResponse response = new BasicResponse(); BasicRequest request = new BasicRequest(); final BasicProperties props = delivery.getProperties(); final BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); try { final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>( BasicRequest.class); decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder); request = avroReader.read(request, decoder); response = RequestProcessor.process(request); } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in handling request: " + e.getMessage()); response = ResponseFactory.getErrorResponse(request); } finally { baos.reset(); final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>( BasicResponse.class); encoder = EncoderFactory.get().binaryEncoder(baos, encoder); avroWriter.write(response, encoder); encoder.flush(); LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus()); channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in RPC server: " + e.getMessage()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
License:MIT License
@Test public void invoke_onOkRequest_correctDataPassedToPublisher() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Map<String, Object> headers = Maps.newHashMap(); headers.put("key", Integer.valueOf(12341234)); Channel channel = mock(Channel.class); doAnswer(invocation -> {// www . ja va2 s .c o m assertEquals(DEFAULT_RPC_EXCHANGE, invocation.getArguments()[0]); assertEquals(Req.class.getName(), invocation.getArguments()[1]); BasicProperties props = (BasicProperties) invocation.getArguments()[2]; assertEquals(instanceId, props.getAppId()); assertEquals(instanceId, props.getReplyTo()); assertEquals(CONTENT_TYPE, props.getContentType()); assertEquals(headers.get("key"), props.getHeaders().get("key")); assertEquals(ENCODING, props.getContentEncoding()); String actual = new String((byte[]) invocation.getArguments()[3]); assertEquals(new String(serializer.encode(req)), actual); return null; }).when(channel).basicPublish(anyString(), any(), any(), any()); CompletableFuture<Res> answer = new CompletableFuture<>(); ResponseReceiver receiver = mock(ResponseReceiver.class); doReturn(answer).when(receiver).put(anyString(), any()); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); doReturn(DEFAULT_RPC_EXCHANGE).when(channelProvider).rpcExchange(); RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver, new DefaultRequestRouter(), new UidGenerator() { }, serializer, headers); invoker.invoke(req, Res.class); // make sure it was invoked, otherwise our assertions will be void verify(channel).basicPublish(anyString(), any(), any(), any()); }
From source file:io.ventu.rpc.amqp.AmqpResponderImpl.java
License:MIT License
CompletableFuture<Void> handleDeliveryInternal(String consumerTag, Envelope envelope, BasicProperties props, byte[] body) { CompletableFuture<byte[]> answer = handleDelivery(envelope.getRoutingKey(), props.getHeaders(), body); return answer.handleAsync((payload, throwable) -> { try {/*from www . j av a 2 s . c om*/ if (throwable != null) { payload = String.format("{\"error\": \"Unhandled internal error: %s\"}", throwable.getMessage()) .getBytes(); } BasicProperties resprops = new Builder().correlationId(props.getCorrelationId()) .contentType(CONTENT_TYPE).contentEncoding(ENCODING).build(); channel.basicPublish(channelProvider.rpcExchange(), props.getReplyTo(), resprops, payload); } catch (IOException e) { // this is suppressed in the public call throw new IllegalStateException(e); } return null; }); }