RabbitMQ学习--HelloWorld(Java)

RabbitMQ消息队列实战
本文详细介绍了如何使用RabbitMQ实现消息队列的基本操作,包括通过amqp-client库在Java环境中配置生产者和消费者,实现消息的发送与接收,并解决了权限问题导致的vhost访问障碍。

amqp-client下载:http://mvnrepository.com/artifact/com.rabbitmq/amqp-client

依赖Jar包:

    <dependency>
         <groupId>com.rabbitmq</groupId>  
         <artifactId>amqp-client</artifactId>  
         <version>3.5.0</version>
     </dependency>

生产者代码Send.java

package com.gdf.example.rabbitmq.helloworld;

import java.io.IOException;

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

public class Send {
	private final static String QUEUE_NAME = "hello";
	
	public static void main(String[] args) throws Exception  {
		// TODO Auto-generated method stub
		ConnectionFactory factory = new ConnectionFactory();
	    factory.setHost("192.168.1.106");
	    factory.setUsername("admin");
	    factory.setPassword("admin");
	    factory.setPort(AMQP.PROTOCOL.PORT);
	    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("UTF-8"));
	    System.out.println(" [x] Sent '" + message + "'");

	    channel.close();
	    connection.close();
	}

}

消费者代码Recv.java

package com.gdf.example.rabbitmq.helloworld;

import java.io.IOException;

import com.rabbitmq.client.AMQP;
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 Recv {
	private final static String QUEUE_NAME = "hello";
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		ConnectionFactory factory = new ConnectionFactory();
	    factory.setHost("192.168.1.106");
	    factory.setUsername("admin");
	    factory.setPassword("admin");
	    factory.setPort(AMQP.PROTOCOL.PORT);
	    Connection connection = factory.newConnection();
	    Channel channel = connection.createChannel();
	    
	    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);
	}

}

问题解决:

由于权限问题导致无法访问vhost/ https://mp.youkuaiyun.com/postedit/81517148

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值