SpringCloud(六)RabbitMQ
同步调用
异步调用
同步、异步选择
同步:对并发没有太多要求且对时效性较高,比如查到某个信息在下一模块立马又要用到,此时在项目中会选择同步。
异步:不关心结果,只是要完成某个事件,并且对吞吐量、并发较高,这时就会选择异步。
RabbitMQ安装部署
安装部署指南
链接:https://pan.baidu.com/s/1Qunzk-cdgXk-nhzmayFDDg
提取码:liub
rabbitmq.tar包
链接:https://pan.baidu.com/s/1BpxziWZR7t5QCBfQB5Cxew
提取码:e6j3
rabbitmq镜像启动后,可通过 服务器/虚拟机IP:15672 来登录rabbitmq控制台。如图:
RabbitMQ结构说明:
RabbitMQ-Demo
案例代码:链接:https://pan.baidu.com/s/1sUxB4pf_ChLUi8oArmyj9Q 提取码:525q
public class PublisherTest { @Test public void testSendMessage() throws IOException, TimeoutException { // 1.建立连接 ConnectionFactory factory = new ConnectionFactory(); // 1.1.设置连接参数,分别是:主机名、端口号、vhost、用户名、密码 factory.setHost("192.168.150.101"); factory.setPort(5672); factory.setVirtualHost("/"); factory.setUsername("itcast"); factory.setPassword("123321"); // 1.2.建立连接 Connection connection = factory.newConnection(); // 2.创建通道Channel Channel channel = connection.createChannel(); // 3.创建队列 String queueName = "simple.queue"; channel.queueDeclare(queueName, false, false, false, null); // 4.发送消息 String message = "hello, rabbitmq!"; channel.basicPublish("", queueName, null, message.getBytes()); System.out.println("发送消息成功:【" + message + "】"); // 5.关闭通道和连接 channel.close(); connection.close(); } }
public class ConsumerTest { public static void main(String[] args) throws IOException, TimeoutException { // 1.建立连接 ConnectionFactory factory = new ConnectionFactory(); // 1.1.设置连接参数,分别是:主机名、端口号、vhost虚拟机、用户名、密码 factory.setHost("192.168.150.101"); factory.setPort(5672); factory.setVirtualHost("/"); factory.setUsername("itcast"); factory.setPassword("123321"); // 1.2.建立连接 Connection connection = factory.newConnection(); // 2.创建通道Channel Channel channel = connection.createChannel(); // 3.创建队列 String queueName = "simple.queue"; channel.queueDeclare(queueName, false, false, false, null); // 4.订阅消息 channel.basicConsume(queueName, true, new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { // 5.处理消息 String message = new String(body); System.out.println("接收到消息:【" + message + "】"); } }); System.out.println("等待接收消息。。。。"); } }