当然首先第一步就是连接上 确保自己端口开放 (5672(消息端口)和 15672(web界面端口)) 我这个是虚拟机中安装好的 导入依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.4.3</version>
</dependency>
创建连接工具类
package com.Utils;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConnectionUtils {
public static Connection getConnection() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.127.132");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
return factory.newConnection();
}
}
最普通的模式
先试着发送消息
package com.han;
import com.Utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
public class publish {
public static void main(String[] args) throws Exception {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("queue7" ,false,false,false,null);
String message = "卧槽了";
channel.basicPublish("" ,"queue7" ,null ,message.getBytes());
System.out.println("消息发送成功");
channel.close();
connection.close();
}
}
然后接收消息
package com.han;
import com.Utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.*;
import java.io.IOException;
public class ReceiveMsg {
public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body);
System.out.println("接收到数据:"+msg);
}
};
channel.basicConsume("queue7",true,consumer);
}
}
|