use of com.rabbitmq.client.DefaultConsumer in project uavstack by uavorg.
the class DoTestRabbitmqProxy method main.
public static void main(String[] args) {
ConsoleLogger cl = new ConsoleLogger("test");
cl.setDebugable(true);
UAVServer.instance().setLog(cl);
UAVServer.instance().putServerInfo(CaptureConstants.INFO_APPSERVER_VENDOR, ServerVendor.TOMCAT);
RabbitmqHookProxy p = new RabbitmqHookProxy("test", Collections.emptyMap());
p.doInstallDProxy(null, "testApp");
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setHost("127.0.0.1");
factory.setPort(5672);
try {
conn = factory.newConnection();
channel = conn.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.queueDeclare("aaa", false, false, false, null);
new Thread(new Runnable() {
@Override
public void run() {
String message = "Hello World!";
while (true) {
try {
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
// System.out.println(" [x] Sent '" + message + "'");
channel.basicPublish("", "aaa", null, "aaame".getBytes("UTF-8"));
// System.out.println(" [x] Sent 'aaame'");
Thread.sleep(1000);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
Connection connection = factory.newConnection();
Channel recvchannel = connection.createChannel();
recvchannel.queueDeclare(QUEUE_NAME, false, false, false, null);
recvchannel.queueDeclare("aaa", false, false, false, null);
Consumer consumer = new DefaultConsumer(recvchannel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
// System.out.println(" [x] Received '" + message + "'1");
}
};
recvchannel.basicConsume(QUEUE_NAME, true, consumer);
String consumerTag = recvchannel.basicConsume("aaa", true, consumer);
try {
Thread.sleep(50000);
recvchannel.basicCancel(consumerTag);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
use of com.rabbitmq.client.DefaultConsumer in project rabbitmq-jms-client by rabbitmq.
the class SimpleServerConnectionIT method testRabbitConnection.
@Test
public void testRabbitConnection() throws Exception {
final Channel channel = this.getConnection().createChannel();
try {
channel.exchangeDeclare("exchangeName", "direct", true);
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, "exchangeName", "routingKey");
byte[] messageBodyBytes = "Hello, world!".getBytes();
channel.basicPublish("exchangeName", "routingKey", null, messageBodyBytes);
boolean autoAck = false;
channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
long deliveryTag = envelope.getDeliveryTag();
// (process the message components here
// ...)
System.out.println("Received Message:" + new String(body));
channel.basicAck(deliveryTag, false);
}
});
Thread.sleep(1000);
} finally {
channel.exchangeDelete("exchangeName");
channel.close();
}
}
use of com.rabbitmq.client.DefaultConsumer in project spring_boot by hryou0922.
the class RpcClient method execute.
public static void execute(String host, String userName, String password, String message) {
// 配置连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
// 需要在管理后台增加一个hry帐号
factory.setUsername(userName);
factory.setPassword(password);
Connection connection = null;
Channel channel = null;
try {
// 建立TCP连接
connection = factory.newConnection();
// 在TCP连接的基础上创建通道
channel = connection.createChannel();
// 定义临时队列,并返回生成的队列名称
String replyQueueName = channel.queueDeclare().getQueue();
// 唯一标志本次请求
String corrId = UUID.randomUUID().toString();
// 生成发送消息的属性
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(// 唯一标志本次请求
corrId).replyTo(// 设置回调队列
replyQueueName).build();
// 发送消息,发送到默认交换机
channel.basicPublish("", RPC_QUEUE_NAME, props, message.getBytes("UTF-8"));
System.out.println(" [RpcClient] Requesting : " + message);
// 阻塞队列,用于存储回调结果
final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
// 定义消息的回退方法
channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
if (properties.getCorrelationId().equals(corrId)) {
response.offer(new String(body, "UTF-8"));
}
}
});
// 获取回调的结果
String result = response.take();
System.out.println(" [RpcClient] Result:'" + result + "'");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 空值判断,为了代码简洁略
channel.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
use of com.rabbitmq.client.DefaultConsumer in project flux by eclipse.
the class RabbitMQMessageConnector method createInbox.
private String createInbox() throws IOException {
DeclareOk ok = this.channel.queueDeclare("", /*durable*/
false, /*exclusive*/
false, /*autoDelete*/
true, null);
final String inbox = ok.getQueue();
console.log("Inbox created: " + inbox);
channel.basicConsume(inbox, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
try {
JSONObject obj = JSON.parse(body);
if (!isSelfOriginated(obj)) {
handleIncomingMessage(obj.getString("type"), obj.getJSONObject("data"));
}
} catch (Exception e) {
console.log(e);
}
}
/**
* Tests whether an incoming message originated from the same MessageConnector that
* is receiving it. (Such messages are skipped in keeping with how socketio does the same
* thing).
*/
private boolean isSelfOriginated(JSONObject obj) {
try {
String origin = obj.getString("origin");
return inbox.equals(origin);
} catch (Exception e) {
console.log(e);
}
return false;
}
});
return inbox;
}
use of com.rabbitmq.client.DefaultConsumer in project cloudstack by apache.
the class RabbitMQEventBus method subscribe.
/**
* Call to subscribe to interested set of events
*
* @param topic defines category and type of the events being subscribed to
* @param subscriber subscriber that intends to receive event notification
* @return UUID that represents the subscription with event bus
* @throws EventBusException
*/
@Override
public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException {
if (subscriber == null || topic == null) {
throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
}
// create a UUID, that will be used for managing subscriptions and also used as queue name
// for on the queue used for the subscriber on the AMQP broker
UUID queueId = UUID.randomUUID();
String queueName = queueId.toString();
try {
String bindingKey = createBindingKey(topic);
// store the subscriber details before creating channel
s_subscribers.put(queueName, new Ternary(bindingKey, null, subscriber));
// create a channel dedicated for this subscription
Connection connection = getConnection();
Channel channel = createChannel(connection);
// create a queue and bind it to the exchange with binding key formed from event topic
createExchange(channel, amqpExchangeName);
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, amqpExchangeName, bindingKey);
// register a callback handler to receive the events that a subscriber subscribed to
channel.basicConsume(queueName, s_autoAck, queueName, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
if (queueDetails != null) {
EventSubscriber subscriber = queueDetails.third();
String routingKey = envelope.getRoutingKey();
String eventSource = getEventSourceFromRoutingKey(routingKey);
String eventCategory = getEventCategoryFromRoutingKey(routingKey);
String eventType = getEventTypeFromRoutingKey(routingKey);
String resourceType = getResourceTypeFromRoutingKey(routingKey);
String resourceUUID = getResourceUUIDFromRoutingKey(routingKey);
Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID);
event.setDescription(new String(body));
// deliver the event to call back object provided by subscriber
subscriber.onEvent(event);
}
}
});
// update the channel details for the subscription
Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
queueDetails.second(channel);
s_subscribers.put(queueName, queueDetails);
} catch (AlreadyClosedException closedException) {
s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", closedException);
} catch (ConnectException connectException) {
s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", connectException);
} catch (Exception e) {
throw new EventBusException("Failed to subscribe to event due to " + e.getMessage());
}
return queueId;
}
Aggregations