public static void main(String[] args) throws IOException, TimeoutException {
// 连接工厂
ConnectionFactory factory = new ConnectionFactory();
// 配置连接属性
factory.setHost("192.168.31.244"); // 虚拟机地址
factory.setPort(5672); // 端口号
factory.setUsername("root"); // 用户名
factory.setPassword("root"); // 密码
// 得到连接,创建通道
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// 声明一个叫Hello.rabbitMQ的队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello RabbitMQ";
// 发送消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
// 关闭通道和连接
channel.close();
connection.close();
}
}
执行完成以后切换到浏览器的管理页面:
我们发现刚才在main函数中声明的QUEUE NAME已经出现了。
2.Spring AMQP——与Spring Boot集成
Maven依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
Spring Boot启动项,声明测试队列:
package org.dispatcher;
import org.springframework.amqp.core.Queue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DispatcherApplication {
@Bean
public Queue helloQueue() {
return new Queue("helloQueue");
}
public static void main(String[] args) throws Exception {
SpringApplication.run(DispatcherApplication.class, args);
}
}
消息生产者:
package org.dispatcher.controller;
import java.util.Date;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Producer {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String sendMsg = "Hi~ " + new Date();
this.rabbitTemplate.convertAndSend("helloQueue", sendMsg);
}
}
消息接收者:
package org.dispatcher.controller;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "helloQueue")
public class Receiver {
@RabbitHandler
public void process(String msg) {
System.out.println("Receiver: " + msg);
}
}
Restful接口:
package org.dispatcher.controller;