org.bitbucket.gkutiel.Bus Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rabbitpubsub Show documentation
Show all versions of rabbitpubsub Show documentation
A simple pub-sub library on top of the RabbitMQ infrastructure.
package org.bitbucket.gkutiel;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.IOException;
import org.slf4j.Logger;
import com.google.gson.Gson;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
class Bus {
private final Channel channel = openChannel();
private final String EXCHANGE = "default";
private final Gson gson = new Gson();
private final Logger log = getLogger(Bus.class);
private void addConsumer(final Class type, final Callback on, final String name) throws IOException {
final DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override public void handleDelivery(final String tag, final Envelope env, final BasicProperties props,
final byte[] body) throws IOException {
on.event(gson.fromJson(new String(body), type));
}
};
channel.basicConsume(name, consumer);
}
private Channel openChannel() {
try {
final ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
final Channel c = factory.newConnection().createChannel();
c.exchangeDeclare(EXCHANGE, "direct");
return c;
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
void pub(final String channelName, final T val) {
try {
final String json = gson.toJson(val);
log.info("pub event key {} val {}", channelName, json);
channel.basicPublish(EXCHANGE, channelName, null, json.getBytes("utf-8"));
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
void sub(final String channelName, final Class type, final Callback on) {
try {
final String name = channel.queueDeclare().getQueue();
channel.queueBind(name, EXCHANGE, channelName);
addConsumer(type, on, name);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
}