RabbitMQ使用教程

上一节RabbitMQ下载和安装结束

输入网站:http://localhost:15672即可访问

采用java代码创建一个生产者和消费者

import java.io.IOException;
import java.util.concurrent.TimeoutException;

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

	

public class Provider {
	
	//定义队列
	static String QUEUE_NAME = "helloRabbit";
	
    public static void main(String[] args) {
		
    	ConnectionFactory factory = new ConnectionFactory();
    	
    	factory.setHost("localhost");
    	//factory.setPort(15672);
    	factory.setUsername("rabbitmq");
    	factory.setPassword("111111");
    	Connection connection = null;
    	Channel channel = null;
    	try{
    	//1、创建连接和通道
    	   connection = factory.newConnection();
    	   channel = connection.createChannel();
    	//2、为通道声明队列
    	   /*@param String queue 队列名
    	    *@param boolean durable 该队列是否需要持久化
    	    *@param boolean exclusive 该队列是否为该通道独占的(其他通道是否可以消费该队列)
    	    *@param boolean autoDelete 该队列不再使用的时候,是否让RabbitMQ服务器自动删除掉
    	    *@param Map arguments 其他参数
    	    */
    	   
    	   channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    	//3、发布消息
    	   String msg = " hello rabbitmq, welcome to sam's blog.";
    	   /*
    	    * @param String exchange 路由器(有的资料翻译成交换机)的名字,即将消息发到哪个路由器
    	    * @param String routingKey 路由键,即发布消息时,该消息的路由键是什么
    	    * @param BasicProperties props 指定消息的基本属性
    	    * @param byte[] body 消息体,也就是消息的内容,是字节数组
    	    */
    	   channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
    	   System.out.println("provider send a msg: " + msg);
    	}catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
        	//4、关闭连接
        	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();
                }
            }
        }
    	
    	
	}
}
import java.io.IOException;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;


public class HellowConsumer {
	
	public static void main(String[] args) {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
    	//factory.setPort(15672);
    	factory.setUsername("rabbitmq");
    	factory.setPassword("111111");
		Connection connection = null;
		Channel channel = null;
		
		try{
			//1、创建连接和通道
			connection = factory.newConnection();
			channel = connection.createChannel();
			//2、为通道声明队列
			channel.queueDeclare(Provider.QUEUE_NAME, false, false, false, null);
			System.out.println(" **** keep alive ,waiting for messages, and then deal them");
			//3、通过回调生成消费者
			Consumer consumer = new DefaultConsumer(channel){
				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
						byte[] body) throws IOException {
					super.handleDelivery(consumerTag, envelope, properties, body);
					//获取消息内容然后处理
					String msg = new String(body, "UTF-8");
					System.out.println("*********** HelloConsumer" + " get message :[" + msg +"]");
					
				}
				
			};
			//4、消费消息
			/**
			 * @param String queue, 队列名字,即要从哪个队列中接收消息
			 * @param boolean autoAck, 是否自动确认,默认true
			 * @param Consumer callback 消费者,即谁接收消息。
			 */
			channel.basicConsume(Provider.QUEUE_NAME, true, consumer);
			
		}catch (Exception e) {
			// TODO: handle exception
		}
		
	}

}

运行时报错:

[AMQP Connection 0:0:0:0:0:0:0:1:5672] WARN com.rabbitmq.client.impl.ForgivingExceptionHandler - An unexpected connection driver error occured (Exception message: Connection reset)
[AMQP Connection 127.0.0.1:5672] ERROR com.rabbitmq.client.impl.ForgivingExceptionHandler - An unexpected connection driver error occured
java.net.SocketException: Socket Closed
	at java.net.SocketInputStream.socketRead0(Native Method)
	at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
	at java.net.SocketInputStream.read(SocketInputStream.java:171)
	at java.net.SocketInputStream.read(SocketInputStream.java:141)
	at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
	at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
	at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:288)
	at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:91)
	at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:184)
	at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:598)
	at java.lang.Thread.run(Thread.java:748)

解决方案:

由于rabbitmq这个用户只分配了角色,没有授权,读写权限:

采用命令授权:

rabbitmqctl set_permissions -p / rabbitmq .* .* .*

RabbitMQ使用教程_第1张图片

成功结果:

你可能感兴趣的:(服务器教程)