- mq版本(maven)
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.9.0</version>
</dependency>
2.java代码 生产者 direct模式
1).创建连接
public static Connection getConnection(){
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("rabbit"); //用户名
factory.setPassword("rabbit"); //密码
factory.setVirtualHost("/"); //虚拟host
factory.setHost("127.0.0.1"); //ip
factory.setPort(5672);
Connection conn = null;
try {
conn = factory.newConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return conn;
}
2).发送消息
public static void sendMsg(String msg) throws Exception {
Connection connection = null;
Channel channel = null;
try {
connection = RabbitUtil.getConnection();
channel = connection.createChannel();
//channel.exchangeDeclare("zhangsan", "direct", true);//声明exchange 类型 持久化
//String queueName = channel.queueDeclare().getQueue();
channel.queueDeclare("zhangsan",true,false,false,null); //声明队列
//channel.queueBind("zhangsan","zhangsan","zs"); //队列名称 exchange名称 routingkey名称
//dircet模式 routerkey默认就是队列名称
channel.basicPublish("","zhangsan",null,msg.getBytes(StandardCharsets.UTF_8)); //发布消息 exchange名称 routingkey名称 null 消息bytes
//channel.queuePurge("zhangsan");//清理队列内数据
} catch (Exception e) {
e.printStackTrace();
} finally {
if (channel != null) {
channel.close();//关闭连接
}
if (connection != null) {
connection.close();//关闭连接
}
}
}
注意:不要多线程公用同一通道,可能会出现线程安全等问题
可以使用spring AMQP 的通道池,尽量不要手动编码管理
3.消费者代码
Connection connection = RabbitUtil.getConnection();
Channel channel = connection.createChannel();
//队列名称 自动ack 接受消息代码
channel.basicConsume("zhangsan",true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String str = new String(body, "UTF-8"); //byte转成字符串
System.out.println(str);
}
});
4.发送消息 faount模式
1)交换机和队列绑定
Connection connection = RabbitUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("amq.fanout","fanout",true); //交换机名称 类型 持久化
channel.queueBind("zhangsan","amq.fanout",""); //交换机队列绑定
channel.queueBind("test111gg","amq.fanout",""); // 交换机队列绑定
channel.close();
connection.close();
//FaountMsg.sendMsg("王五哇。"); //发送消息
2)发送消息
Connection connection = RabbitUtil.getConnection();
Channel channel = connection.createChannel();
channel.basicPublish("amq.fanout","",null,msg.getBytes(StandardCharsets.UTF_8));