Server
public class Main { public static void main(String[] args) throws IOException, TimeoutException { String queueName="Hello"; ConnectionFactory factory=new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(queueName,false,false,false,null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer=new DefaultConsumer(channel){ @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 + "'"); } }; channel.basicConsume(queueName,true,consumer); } }
Client
public class Main { public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { String queueName="Hello"; ConnectionFactory factory=new ConnectionFactory(); factory.setHost("localhost"); Connection connection= factory.newConnection(); Channel channel= connection.createChannel(); channel.queueDeclare(queueName,false,false,false,null); int count=0; while (count<100){ Date date=new Date(); String message=String.format("Hello World : %s", date.toString()); channel.basicPublish("",queueName,null,message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); count++; Thread.sleep(1000); } channel.close(); connection.close(); } }
References
https://www.rabbitmq.com/tutorials/tutorial-one-java.html
https://github.com/mhdr/RabbitMQSamples/tree/master/001_HelloWorld