List of usage examples for org.springframework.amqp.core MessageProperties setCorrelationId
public void setCorrelationId(String correlationId)
From source file:com.jbrisbin.vpc.jobsched.mapred.ReplyClosure.java
@Override public Object call(final Object obj) { log.debug("obj: " + obj); String replyTo = (String) getProperty("replyTo"); if (null != replyTo) { rabbitTemplate.send("", replyTo, new MessageCreator() { public Message createMessage() { MessageProperties props = new RabbitMessageProperties(); props.setContentType("application/json"); props.setCorrelationId(getProperty("id").toString().getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mapper.writeValue(out, obj); } catch (IOException e) { log.error(e.getMessage(), e); }//from w ww .j a v a 2 s . c o m Message msg = new Message(out.toByteArray(), props); if (log.isDebugEnabled()) { log.debug("Sending reply: " + msg); } return msg; } }); } else { log.warn("Reply requested, but replyTo was null!"); } return null; }
From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageConverter.java
public Message toMessage(Object object, MessageProperties props) throws MessageConversionException { if (object instanceof SqlMessage) { SqlMessage msg = (SqlMessage) object; props.setCorrelationId(msg.getId().getBytes()); byte[] bytes; try {/* ww w .j a va 2 s . c o m*/ bytes = unmapObject(msg.getResults()); } catch (IOException e) { throw new MessageConversionException(e.getMessage(), e); } props.setContentType("application/json"); return new Message(bytes, props); } else { throw new MessageConversionException( "Cannot convert object " + String.valueOf(object) + " using " + getClass().toString()); } }
From source file:com.jbrisbin.vpc.jobsched.batch.BatchMessageConverter.java
public Message toMessage(Object object, MessageProperties props) throws MessageConversionException { if (object instanceof BatchMessage) { BatchMessage batch = (BatchMessage) object; props.setCorrelationId(batch.getId().getBytes()); props.setContentType("application/zip"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ZipOutputStream zout = new ZipOutputStream(bout); for (Map.Entry<String, String> msg : batch.getMessages().entrySet()) { ZipEntry zentry = new ZipEntry(msg.getKey()); try { zout.putNextEntry(zentry); zout.write(msg.getValue().getBytes()); zout.closeEntry();//from w w w. j av a 2s . co m } catch (IOException e) { throw new MessageConversionException(e.getMessage(), e); } } try { zout.flush(); zout.close(); } catch (IOException e) { throw new MessageConversionException(e.getMessage(), e); } return new Message(bout.toByteArray(), props); } else { throw new MessageConversionException( "Cannot convert object " + String.valueOf(object) + " using " + getClass().toString()); } }
From source file:weChat.amqp.RpcTest.java
/** * Sends a message to a service that upcases the String and returns as a * reply using a {@link RabbitTemplate} configured with a fixed reply queue * and reply listener, configured with JavaConfig. *///from ww w. j a va 2 s . c om @Test public void test() { AmqpReqParam param = new AmqpReqParam(); param.setCmdid("WJ007"); param.setCompanycode("01103"); param.setWechatpubinfoid(1); BaseDto dto = new BaseDto(); dto.put("cardnum", "5000011"); param.setParams(dto); //String corrId = UUID.randomUUID().toString(); String corrId = FixedReplyQueueConfig.responseQueue; Object resp = rabbitTemplate.convertSendAndReceive(FixedReplyQueueConfig.routing, param, (message) -> { MessageProperties properities = message.getMessageProperties(); System.out.println("corrId:" + corrId); properities.setCorrelationId(corrId.getBytes()); properities.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); properities.setTimestamp(new Date()); long currentTimeMillis = System.currentTimeMillis(); properities.setMessageId(String.valueOf(currentTimeMillis)); properities.setExpiration(String.valueOf(50000)); properities.setContentEncoding(corrId); return message; }); System.out.println("?" + resp); }
From source file:weChat.amqp.JavaConfigFixedReplyQueueTests.java
/** * Sends a message to a service that upcases the String and returns as a * reply using a {@link RabbitTemplate} configured with a fixed reply queue * and reply listener, configured with JavaConfig. *//*from w w w. jav a 2 s .c om*/ @Test public void test() { AmqpReqParam param = new AmqpReqParam(); param.setCmdid("WJ007"); param.setCompanycode("00111"); param.setWechatpubinfoid(1); BaseDto dto = new BaseDto(); dto.put("cardnum", "5000028"); param.setParams(dto); AmqpRespParam resp = (AmqpRespParam) rabbitTemplate.convertSendAndReceive(param, (message) -> { MessageProperties properities = message.getMessageProperties(); String corrId = UUID.randomUUID().toString(); properities.setCorrelationId(corrId.getBytes()); properities.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); properities.setTimestamp(new Date()); long currentTimeMillis = System.currentTimeMillis(); properities.setMessageId(String.valueOf(currentTimeMillis)); return message; }); System.out.println(resp); }
From source file:com.jbrisbin.vpc.jobsched.SubmitClosure.java
@Override public Object call(Object[] args) { log.debug("args: " + args); String exch = args[0].toString(); String route = args[1].toString(); final Object body = args[2]; Map headers = null;//from ww w . j av a 2 s .com final BlockingQueue<Object> resultsQueue = new LinkedBlockingQueue<Object>(); Queue replyQueue = rabbitAdmin.declareQueue(); SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(); listener.setQueues(replyQueue); if (args.length > 3) { for (int i = 3; i <= args.length; i++) { if (args[i] instanceof MessageListener) { MessageListener callback = (MessageListener) args[3]; listener.setMessageListener(callback); } else if (args[i] instanceof Map) { headers = (Map) args[i]; } } } else { listener.setMessageListener(new MessageListener() { public void onMessage(Message message) { byte[] body = message.getBody(); try { resultsQueue.add(mapper.readValue(body, 0, body.length, Map.class)); } catch (IOException e) { log.error(e.getMessage(), e); } } }); } final Map msgHdrs = headers; rabbitTemplate.send(exch, route, new MessageCreator() { public Message createMessage() { MessageProperties props = new RabbitMessageProperties(); props.setContentType("application/json"); if (null != msgHdrs) { props.getHeaders().putAll(msgHdrs); } String uuid = UUID.randomUUID().toString(); props.setCorrelationId(uuid.getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mapper.writeValue(out, body); } catch (IOException e) { log.error(e.getMessage(), e); } Message msg = new Message(out.toByteArray(), props); return msg; } }); Object results = null; try { results = resultsQueue.poll(5, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error(e.getMessage(), e); } listener.stop(); return results; }
From source file:com.jbrisbin.vpc.jobsched.RequeueJob.java
public void maybeRequeue() { RequestMeta meta = new RequestMeta(); meta.setQueryParam("keys", "true"); BucketResponse bucket = riak.listBucket(riakBucket, meta); if (bucket.isSuccess()) { for (String messageId : bucket.getBucketInfo().getKeys()) { FetchResponse response = riak.fetch(riakBucket, messageId); if (response.isSuccess()) { // Try re-queueing message try { if (log.isDebugEnabled()) { log.debug("Requeueing messageId: " + messageId); }/*from w w w. j a v a 2 s .co m*/ final Map<String, Object> message = mapper.readValue(response.getBodyAsString(), Map.class); RabbitTemplate tmpl = appCtx.getBean(RabbitTemplate.class); final MessageProperties props = new RabbitMessageProperties(); Map headers = (Map) message.get("headers"); for (Object key : headers.keySet()) { props.setHeader(key.toString(), headers.get(key)); } props.setCorrelationId(messageId.getBytes()); props.setContentType("application/json"); tmpl.send(message.get("exchange").toString(), message.get("route").toString(), new MessageCreator() { @Override public Message createMessage() { Message msg = new Message(message.get("body").toString().getBytes(), props); if (log.isDebugEnabled()) { log.debug("Sending AMQP message: " + msg.toString()); } return msg; } }); // Delete from nosql store if (log.isDebugEnabled()) { log.debug("Deleting messageId " + messageId + " from requeue cache"); } riak.delete(riakBucket, messageId); } catch (IOException e) { log.error(e.getMessage(), e); } } } } }
From source file:com.jbrisbin.vpc.jobsched.mapred.MapReduceMessageHandler.java
private void onKeyChange(final String id, final String key) { final String token = id + key; Closure cl = contextCache.remove(token); Closure onKeyChange = (Closure) cl.getProperty("onKeyChange"); onKeyChange.setProperty("key", key); final Object o = onKeyChange.call(); if (null != o) { // Send to rereduce rabbitTemplate.send("", DigestUtils.md5Hex(id), new MessageCreator() { public Message createMessage() { MessageProperties props = new RabbitMessageProperties(); props.setContentType("application/json"); props.setCorrelationId(id.getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mapper.writeValue(out, o); } catch (IOException e) { log.error(e.getMessage(), e); }//from ww w . j a v a 2 s. c o m Message msg = new Message(out.toByteArray(), props); return msg; } }); } }
From source file:org.kurento.rabbitmq.RabbitTemplate.java
@SuppressWarnings("unchecked") private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback, final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException { return this.execute(new ChannelCallback<Boolean>() { @Override/*from ww w.j a v a 2s . co m*/ public Boolean doInRabbit(Channel channel) throws Exception { boolean channelTransacted = RabbitTemplate.this.isChannelTransacted(); GetResponse response = channel.basicGet(queueName, !channelTransacted); // Response can be null in the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel); if (channelLocallyTransacted) { channel.basicAck(deliveryTag, false); } else if (channelTransacted) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(), channel, deliveryTag); } Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response); Object receive = receiveMessage; if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) { receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage); } S reply; try { reply = callback.handle((R) receive); } catch (ClassCastException e) { StackTraceElement[] trace = e.getStackTrace(); if (trace[0].getMethodName().equals("handle") && trace[1].getFileName().equals("RabbitTemplate.java")) { throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback + "' can't handle received object '" + receive + "'", e); } else { throw e; } } if (reply != null) { Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply); Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply); MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties(); MessageProperties replyMessageProperties = replyMessage.getMessageProperties(); Object correlation = RabbitTemplate.this.correlationKey == null ? receiveMessageProperties.getCorrelationId() : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey); if (RabbitTemplate.this.correlationKey == null || correlation == null) { // using standard correlationId property if (correlation == null) { String messageId = receiveMessageProperties.getMessageId(); if (messageId != null) { correlation = messageId.getBytes(RabbitTemplate.this.encoding); } } replyMessageProperties.setCorrelationId((byte[]) correlation); } else { replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation); } // 'doSend()' takes care about 'channel.txCommit()'. RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage, null); } else if (channelLocallyTransacted) { channel.txCommit(); } return true; } return false; } }); }
From source file:org.springframework.amqp.rabbit.AsyncRabbitTemplate.java
private String getOrSetCorrelationIdAndSetReplyTo(Message message) { String correlationId;/*w ww .j av a 2 s .co m*/ MessageProperties messageProperties = message.getMessageProperties(); Assert.notNull(messageProperties, "the message properties cannot be null"); String currentCorrelationId = messageProperties.getCorrelationId(); if (!StringUtils.hasText(currentCorrelationId)) { correlationId = UUID.randomUUID().toString(); messageProperties.setCorrelationId(correlationId); Assert.isNull(messageProperties.getReplyTo(), "'replyTo' property must be null"); } else { correlationId = currentCorrelationId; } messageProperties.setReplyTo(this.replyAddress); return correlationId; }