环境搭建
这里使用gradle项目
apply plugin: 'eclipse'
apply plugin: 'maven'
apply plugin: 'java' sourceCompatibility = 1.8
[compileJava,compileTestJava,javadoc]*.options*.encoding = 'UTF-8'
repositories { maven{url 'http://maven.aliyun.com/nexus/content/groups/public/'}
mavenCentral()
jcenter()
}
dependencies {
compile group: 'com.rabbitmq', name: 'amqp-client', version: '4.1.0'
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
}
Hello World模式(点对点)
package com.rabbitmq.www.helloworld; 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"; private final static String HOST_ADDR = "172.18.112.102"; public static void main(String[] args) throws Exception { ConnectionFactory factory = new ConnectionFactory();
factory.setHost(HOST_ADDR);
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("发送消息 : " + message + "'");
channel.close();
connection.close(); } }
package com.rabbitmq.www.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"; private final static String HOST_ADDR = "172.18.112.102"; public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub ConnectionFactory factory = new ConnectionFactory();
factory.setHost(HOST_ADDR);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("等待消息");
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("接受消息 : " + message);
}
};
channel.basicConsume(QUEUE_NAME, true, consumer); } }