mq原理不再赘述,百度一下大把介绍。但很难找到简单实用易理解的实例,故写此博客。
说明:本实例使用的是两个最基本的Java项目,开始吧
第一步:RabbitMq实例所用到的jar包
请先下载这三个jar包
http://central.maven.org/maven2/com/rabbitmq/amqp-client/5.5.1/amqp-client-5.5.1.jar
http://central.maven.org/maven2/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar
http://central.maven.org/maven2/org/slf4j/slf4j-simple/1.7.25/slf4j-simple-1.7.25.jar
第二部:直接上代码
项目1(名字随便起):
创建一个producer类
/**
* Created by DonviYang on 2019/1/9.
*/
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;
public class producer {
private final static String QUEUE_NAME = "HELLO";
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try(Connection connection = factory.newConnection();
Channel channel = connection.createChannel()){
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String message = "hello rabbitMq!" + new Date();
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println(" [x] sent '" + message +"'");
} catch (TimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
项目2:
创建一个consumer类
/**
* Created by DonviYang on 2019/1/9.
*/
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class consumer {
private final static String QUEUE_NAME = "HELLO";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
System.out.println(" [*] Waiting for message. To exit press CTRL+C ");
DeliverCallback deliverCallback = (consumerTag,delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Receive '" + message + "'");
};
channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumerTag -> { });
}
}