2019独角兽企业重金招聘Python工程师标准>>>
1 导入依赖
4.0.0
com.shi.rabbitmq
rabbitmq-01
0.0.1-SNAPSHOT
com.rabbitmq
amqp-client
3.4.1
org.slf4j
slf4j-log4j12
1.7.7
org.apache.commons
commons-lang3
3.3.2
org.springframework.amqp
spring-rabbit
1.4.0.RELEASE
junit
junit
4.12
test
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
2 工具类
package com.shi.util;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* 创建工厂类--rabbitMq
* @author SHF
* @version 创建时间:2018年7月3日 上午9:49:57
*/
public class RabbitMqUtils {
private static String host = "127.0.0.1";
private static Integer port = 5672;
private static String userName = "shiye";
private static String pwd = "shiye";
private static String vhost = "/test";
public static Connection getConnection() throws IOException, TimeoutException{
//1 定义链接工厂
ConnectionFactory factory = new ConnectionFactory();
//2 设置服务器地址,端口,账户信息,用户名,密码,vhost
factory.setHost(host);
factory.setPort(port);
factory.setVirtualHost(vhost);
factory.setUsername(userName);
factory.setPassword(pwd);
//3 通过工厂获取链接
Connection connection = factory.newConnection();
return connection;
}
}
3 生产者
/**
* 生产者
* @author SHF
* @version 创建时间:2018年7月3日 上午10:08:57
* @throws TimeoutException
* @throws IOException
*/
@Test
public void producer() throws IOException, TimeoutException {
//1 获取链接以及mq通道
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
//2 申明队列
DeclareOk queueOK = channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//3 添加消息内容
String message = "Hello World; 施爷";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println( "sent: '" + message + "'");
//关闭通道和连接
channel.close();
connection.close();
}
4 消费者
/**
* 消费者
* @author SHF
* @version 创建时间:2018年7月3日 上午11:03:25
* @throws Exception
*/
@Test
public void Consum() throws Exception{
//1 获取链接及mq通道,
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
//2 申明队列(如果存在就不创建)
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//3 定义队列的消费者
QueueingConsumer cunusumer = new QueueingConsumer(channel);
//4 监听队列
channel.basicConsume(QUEUE_NAME, true,cunusumer);
//5 获取消息
while(true) {
Delivery delivery = cunusumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" received: " + message);
}
}