RabbitMQ-HelloWorld

消息队列.png | center | 747x791

上面这个图片, 简单的概述.
下面我们先来个简单的helloworld. (例子均来自官网)
先来看一下生产者的代码:

package com.tgb.kwy.helloworld;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * Description 生产者
 *
 * @author kongwy [email protected]
 * @version 1.0
 * @date 2018-07-08-20 -00
 */
public class Send {
    private final static String QUEUE_NAME="hello";

    public static void main(String[] args) throws java.io.IOException{
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.159.132");/*设置rabbitmq所在主机ip或主机名*/
        /*指定用户名和密码*/
        factory.setUsername("admin");
        factory.setPassword("admin");
        //指定端口
        factory.setPort(AMQP.PROTOCOL.PORT);
        //创建连接
        try{
            Connection connection=factory.newConnection();
            Channel channel=connection.createChannel();
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            String message="Hello World!";
            channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
            channel.close();
            connection.close();
        }catch (Exception e){

        }

    }
}

这里涉及到了ConnectionFactory,Connection,Channel, 上面那个导图,对这三个也有所讲解
ConnectionFactory: Connection的制造工厂
Connection:rabbitmq服务器的socket连接,封装了socket协议及身份验证相关逻辑
channel:大部分api接口,包括了定义queue,exchange等
运行效果:

send.png | center | 299x39

我们来看一下消费者代码:

package com.tgb.kwy.helloworld;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * Description 消费者
 *
 * @author kongwy [email protected]
 * @version 1.0
 * @date 2018-07-08-20 -08
 */
public class Recv {
    private final static String QUEUE_NAME="hello";

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.159.132");
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();
        boolean durable=true;//持久化
        channel.queueDeclare(QUEUE_NAME,durable,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(QUEUE_NAME,true,consumer);
    }
}

运行效果

recv.png | center | 690x55

注:代码来自官网,导图部分内容来自网络.官网对于概念性的内容,讲解的还是很清楚的

猜你喜欢

转载自blog.csdn.net/kwy15732621629/article/details/80995632
今日推荐