Here is a sample of a consumer and producer example for RabbitMQ. The steps are
For more information on AMQP, Exchanges, Queues, read this excellent tutorial
http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
+++++++++++++++++RabbitMQProducer.java+++++++++++++++++++++++++++
See also
- Download Erlang
- Download Rabbit MQ Server
- Download Rabbit MQ Java client jars
- Compile and run the below two class and you are done.
For more information on AMQP, Exchanges, Queues, read this excellent tutorial
http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
+++++++++++++++++RabbitMQProducer.java+++++++++++++++++++++++++++
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.*;
public class RabbitMQProducer {
public static void main(String []args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("127.0.0.1");
factory.setPort(5672);
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
String exchangeName = "myExchange";
String routingKey = "testRoute";
byte[] messageBodyBytes = "Hello, world!".getBytes();
channel.basicPublish(exchangeName, routingKey
,MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes) ;
channel.close();
conn.close();
}
}
+++++++++++++++++RabbitMQConsumer.java+++++++++++++++++++++++++++
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.*;
public class RabbitMQConsumer {
public static void main(String []args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("127.0.0.1");
factory.setPort(5672);
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
String exchangeName = "myExchange";
String queueName = "myQueue";
String routingKey = "testRoute";
boolean durable = true;
channel.exchangeDeclare(exchangeName, "direct", durable);
channel.queueDeclare(queueName, durable,false,false,null);
channel.queueBind(queueName, exchangeName, routingKey);
boolean noAck = false;
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, noAck, consumer);
boolean runInfinite = true;
while (runInfinite) {
QueueingConsumer.Delivery delivery;
try {
delivery = consumer.nextDelivery();
} catch (InterruptedException ie) {
continue;
}
System.out.println("Message received"
+ new String(delivery.getBody()));
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
channel.close();
conn.close();
}
}
See also
Thanks for this, man...
ReplyDeleteThanks I am glad it was useful for someone.
ReplyDelete...
ReplyDeleteThis code it is not valid for the last version RabbitMQ Java API 1.8 :
ReplyDeleteConnectionParameters no longer exists, to make it work it should be changed for:
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername(userName);
factory.setPassword(password);
factory.setVirtualHost(virtualHost);
factory.setHostName(hostName);
factory.setPortNumber(portNumber);
Connection conn = factory.newConnection();
Thanks updated the code.
ReplyDeletecan u let me know how to assign the consumer to a listener which will start listening at the application start up
ReplyDeleteSorry I didn't understood the question properly. But let me answer from what I understood, if you want the application to consumer message as soon as its up, thats what the consumer program I have written does but it does for a simple main program launched at command line. If you want to do it for a web application then you can create a Thread from javax.servlet.ServletContextListener that would do the same. The thread in its run method can do the same loop I am doing in class RabbitMQConsumer.
ReplyDeleteThanks man this is really beneficial for beginner .
ReplyDeleteHi ,
ReplyDeleteI am new to RabbitMQ trying to play with Java. I have a typical problem which shows error as below. I am not sure where it went wrong while executing the .jar file. I try to follow the program above by you but it seems the problem lies somewhere else. Can you help me please.
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:310)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:176)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:163)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at com.rabbitmq.client.ConnectionFactory.createFrameHandler(ConnectionFactory.java:338)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:376)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:399)
Rudra this says connection refused which tells me that your rabbitmq is not up. Did your rabbitmq install went fine? Can you run ps -ef|grep rabbitmq or task manager and see it running?
ReplyDeleteHi Kalpesh ,
ReplyDeleteI tried the command and foud the results below. The daemon thread is running.Can you suggest me what can be done to set it right .
rabbitmq 1252 1 0 09:34 ? 00:00:00 /usr/lib/erlang/erts-5.7.4/bin/epmd -daemon
rudy 7429 7382 0 22:20 pts/0 00:00:00 grep --color=auto rabbitmq
Hey, thanks for the code, very helpful. I can run this on the same machine as the RabbitMQ server but can't connect when I run it on another machine and specify the host or ip address. Any ideas on what I need to do to enable. Failure results in either connection timed out or authentication error.
ReplyDeleteThanks!
Did you checked if there is a Firewall blocking it? I have never seen connection timed out connecting to rabbit server.
ReplyDeleteCan anyone please suggest whether Rabbitmq is a server (or) messaging protocol? Because i tried to start this rabbitmq using command line utility along with the batch files which is there inside the rabbitmq server folder(rabbitmq-server.bat,rabbitmq-service.bat)via console, but it doesn't works for me exactly. Thanks in advance.
ReplyDeleteRabbitMQ is a server and AMQP is the protocol it implements. I suggest you read http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/ for more info.
ReplyDeleteThanks for your help, i went through the link which you sent to me before,please suggest me whether i need to configure this rabbitmq in eclipse sdk (or) else i need to use this via console. I'm trying to do a messaging queue kind of a thing by having one sender and receiver, but i don't know exactly how to do this, and how to run this process on rabbitmq? If anyone know about this please help me over this. Thanks in advance.
DeleteRabbitMQ is like a database server so you have to start it from command line if you are on windows(I havent used on windows), then you write programs to produce/consumer messages from it. So rabbitmq is just a broker.
DeleteAgain thanks for your reply Kalpesh, after writing both the producer as well as consumer java class in eclipse IDE, how i need to see both the sending and receiving messages in rabbitmq console i.e., via localhost in browser. Can any one explain about this process exactly please? Thanks in advance.
DeleteLast I know there was no option to view the queue contents so the trick is to just write a python program that would consume the message but wont acknowledge it. You might check this out http://neopatel.blogspot.com/2010/07/dumping-rabbitmq-queue-contents.html
DeleteSo your are telling that there is no way to see the messaging queue console in rabbitmq via., writing java classes rite? So can you please suggest me any other possible way except (python program) to do a messaging queue kind of thing related to java program? Because i supposed to do this in java. (Already i wrote two java classes one is producer and another one is a consumer class, it is running exactly and i can see the sending and receiving of messages alone in eclipse IDE console and i couldn't see this in rabbitmq console for this process only i need a solution from somebody). Thanks in advance.
ReplyDeleteYes last I know you can only run command all I get is queue sizes.You can replicate the python program I wrote in java as basically you consume the messages but dont acknowledge it.
Delete"kpatel@kpatel-laptop:~$ sudo rabbitmqctl list_queues
[sudo] password for kpatel:
Listing queues ...
thumbnail_gen_queue 0
localhost:8080_bill_queue 0
"
How to read messages from RabbitMQ's queue by having a tomcat server listen at a port without using Sprin framework? Any help is greatly appreciated
ReplyDeleteHow to apply the message selectors in RabbitMQ queue.We can achieve using ActiveMQ functionality
ReplyDelete