本次利用rabbitmq作为中介,实现了简单的消息发送和消费,模式如下:
发送接收模式
官方的介绍文档可以转至链接:https://www.rabbitmq.com/tutorials/tutorial-one-java.html
常量定义:
public interface ExampleConstants { String QUEUE_NAME = "hello"; }
发送端代码:
package com.test.example; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * @Author * @create */ public class Sender { public static void main(String[] args) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = null; Channel channel = null; try{ connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(ExampleConstants.QUEUE_NAME,false,false,false,null); String message = "hello lh"; channel.basicPublish("",ExampleConstants.QUEUE_NAME,null,message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); }catch (Exception e){ e.printStackTrace(); }finally { if(channel != null){ try { channel.close(); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
消费端代码:
package com.test.example; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * @Author * @create */ public class Receiver { public static void main(String[] args) { ConnectionFactory factory = null; Connection connection = null; Channel channel = null; try{ factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(ExampleConstants.QUEUE_NAME,false,false,false,null); DeliverCallback deliverCallback = (consumerTag,delivery) -> { String message = new String(delivery.getBody(),"UTF-8"); System.out.println(" [x] Received '" + message + "'"); }; channel.basicConsume(ExampleConstants.QUEUE_NAME,true,deliverCallback,consumerTag -> {}); }catch (Exception e){ e.printStackTrace(); }finally { if(channel != null){ try { channel.close(); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (IOException e) { e.printStackTrace(); } } } } }