前言
本文简要介绍如何使用java客户端,连接rabbitmq server。本文开始之前,需要安装好mq服务器,如果不知道怎么安装,可参考rabbitmq安装
-
使用架构
使用gradle java项目
代码
- build.gradle
plugins {
id 'java'
}
group 'com.nick'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'com.rabbitmq', name: 'amqp-client', version: '5.2.0'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
compile group: 'org.projectlombok', name: 'lombok', version: '1.18.0'
}
- send 生产者(p)
package com.nick.simpleTest;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeoutException;
public class Send {
private final static String QUEUE_NAME = "hello";
public static Logger logger = LoggerFactory.getLogger(Send.class);
public static void main(String[] argv)
throws java.io.IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.1.249");
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());
logger.info(" [x] Sent '{}'" ,message );
channel.close();
connection.close();
}
}
- receive 消费者(c)
package com.nick.simpleTest;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Recv {
private final static String QUEUE_NAME = "hello";
public static Logger logger = LoggerFactory.getLogger(Recv.class);
public static void main(String[] argv)
throws java.io.IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.1.249");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
logger.info(" [*] 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");
logger.info(" [x] Received '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
测试
- 先运行消费者,再运行生产者,效果截图如下:
完整代码
完整代码可以在github上下载到。