Skip to content

Instantly share code, notes, and snippets.

@tjayr
Last active August 29, 2015 14:07
Show Gist options
  • Save tjayr/0afe40f0bed3f0bd0db7 to your computer and use it in GitHub Desktop.
Save tjayr/0afe40f0bed3f0bd0db7 to your computer and use it in GitHub Desktop.
Java client code showing how to connect to a rabbitmq server, retrieve a message, convert its body to a string and disconnects.
package com.liberty.it.dws;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;
public class AmqClientTest {
private Connection conn;
private final String exchangeName = "test.exchange";
public void connect() {
ConnectionFactory factory = new ConnectionFactory();
try {
factory.setUri("amqp://guest:guest@localhost:5672");
conn = factory.newConnection();
} catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getMessageBodyAsString() {
String response = "";
try {
Channel channel = conn.createChannel();
channel.exchangeDeclare(exchangeName, "direct", true);
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, exchangeName, "requests");
GetResponse objResponse = channel.basicGet("requests", true);
if (objResponse != null) {
response = new String(objResponse.getBody());
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public void disconnect() {
try {
if (conn != null) {
conn.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AmqClientTest test = new AmqClientTest();
test.connect();
System.out.println(test.getMessageBodyAsString());
test.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment