RabbitMQ学习02
Hello World(Java)
1.导入依赖
<!--指定 jdk 编译版本--><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>8</source><target>8</target></configuration></plugin></plugins></build><dependencies><!--rabbitmq 依赖客户端--><dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><version>5.8.0</version></dependency><!--操作文件流的一个依赖--><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></dependency></dependencies>
2.生产者
public class Producer {//队列public static final String QUEUE_NAME = "hello";//发消息public static void main(String[] args) throws IOException, TimeoutException {//创建一个连接工厂ConnectionFactory factory = new ConnectionFactory();//工厂id 连接rabbitMQ队列factory.setHost("192.168.170.150");//用户名factory.setUsername("admin");//密码factory.setPassword("123");//创建连接Connection MQConnection = factory.newConnection();//获取信道Channel channel = MQConnection.createChannel();//交换机/*** 生成一个队列* 1.队列名称* 2.队列里的消息是否持久化(磁盘) 默认情况消息存储在内存中* 3.该队列是否只提供一个消费者消费,是否进行消息共享?true 可以多个消费者* 4.表示是否自动删除 最后一个消费者断开连接后 该队列是否自动删除 true自动删除 false不自动删除* 5.其他参数*/channel.queueDeclare(QUEUE_NAME,false,false,false,null);//发消息String message = "hello rabbitMQ";/*** 发送一个消息* 1.发送给哪个交换机?* 2.路由的key值是什么* 3.其他参数信息* 4.发送的消息的消息体*/channel.basicPublish("",QUEUE_NAME,null,message.getBytes());System.out.println("消息发送完毕");}}
3.消费者
public class Consumer {//队列的名称public static final String QUEUE_NAME = "hello";//接收消息public static void main(String[] args) throws IOException, TimeoutException {//创建连接工厂ConnectionFactory factory = new ConnectionFactory();//工厂id 连接rabbitMQ队列factory.setHost("192.168.170.150");factory.setUsername("admin");factory.setPassword("123");Connection connection = factory.newConnection();Channel channel = connection.createChannel();//声明接收消息DeliverCallback deliverCallback = (consumerTag, message) -> {System.out.println("接收到了消息:" + new String(message.getBody()));};//声明取消消息的回调CancelCallback cancelCallback = (consumerTag) -> {System.out.println("消息消费被中断了");};/*** 消费者消费消息* 1.消费哪个队列* 2.消费成功之后是否要自动应答,true代表的自动应答 false 代表手动应答* 3.消费者未成功消费的回调* 4.取消消费的回调*/channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);}}
上面代码出现了冗余
所以抽取成工具类
public class RabbitMQUtils {public static Channel getChannel() throws Exception{//创建一个连接工厂ConnectionFactory factory = new ConnectionFactory();//工厂id 连接rabbitMQ队列factory.setHost("192.168.170.150");//用户名factory.setUsername("admin");//密码factory.setPassword("123");//创建连接Connection MQConnection = factory.newConnection();//获取信道Channel channel = MQConnection.createChannel();return channel;}
}