您的位置:首页 > 编程语言 > Java开发

rabbitmq学习(java客户端)

2017-11-13 14:48 330 查看
1、rabbitmq采取的是集群安装

2、项目为maven工程,只需要在pom文件中加入:

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


3.源码

(一):Send.class

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

/**
* Created by joyce on 2017/11/13.
*/
public class Send {
private final static String QUEUE_NAME = "test";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("集群中的ip");

factory.setUsername("usrname");
factory.setPassword("passwd");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World! zyy";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}


(二):Recv.class


import com.rabbitmq.client.*;
import java.io.IOException;

/**
* Created by joyce on 2017/11/13.
*/
public class Recv {
private final static String QUEUE_NAME = "test";
public static void main(String[] args) throws  Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("IP");
factory.setUsername("usrname");
factory.setPassword("passwd");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
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);
}
}


(三):直接跑main(),可以在控制台看见输出...




看到我请叫我去写作业_(wechat:jshasmith0826)


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  rabbitmq