https://www.rabbitmq.com/getstarted.html
官网文档
我们将呼叫我们的消息发布者(发送者)发送和我们的消息消费者(接收者) Recv。发布者将连接到RabbitMQ,发送单个消息,然后退出
创建一个Send.java 根据 springboot 配置文件配置
@Component
public class Send {
//设置类命名队列
private final static String QUEUE_NAME = "hello";
@Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.port}")
private int port;
@Value("${spring.rabbitmq.username}")
private String username;
@Value("${spring.rabbitmq.password}")
private String password;
public void send(){
//船舰到服务器的链接
ConnectionFactory factory = new ConnectionFactory();
factory.setPort(port);
factory.setPassword(password);
factory.setUsername(username);
factory.setHost(host);
Connection connection = null;
Channel channel = null;
try{
connection = factory.newConnection();
channel = connection.createChannel() ;
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
for(int i = 0;i<5;i++) {
String value = "hello··········";
channel.basicPublish("", QUEUE_NAME, null, value.getBytes());
}
}catch (Exception e){
}finally {
try {
//关闭链接 不然一直消耗
channel.close();
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
配置文件
########### rabbitmq ############
spring.rabbitmq.host=XXX.xxx.xxx.xx
spring.rabbitmq.port=xxx
spring.rabbitmq.username=xxx
spring.rabbitmq.password=xxx
启动类
@Override public void run(String... args) throws Exception { Send.init(); }
项目启动后 到
查看
发送的信息
消费端接收
public static void main (String [] argv) throws Exception{ //创建服务器的链接 ConnectionFactory factory = new ConnectionFactory(); //创建 factory.setHost("xxxx.xxxx.xxxx.xxxx"); factory.setPassword("guest"); factory.setUsername("guest"); factory.setPort(xxxx); Connection connection = factory.newConnection(); Channel channel = connection.createChannel() ; channel.queueDeclare(QUEUE_NAME,false,false,false,null); DefaultConsumer defaultConsumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String s = new String(body); System.out.println("接受到的消息:"+s); } }; channel.basicConsume(QUEUE_NAME,true,defaultConsumer); }