目录
概述
消息队列内容
1. 轮训发送
2. 消息应答
3. 消息持久化
4. 不公平分发
5. 预期值 -> 不公平分发进阶
轮训发送消息
提取工具类方便后面调用 RabbitMqUtils
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMqUtils {
//得到一个连接的 channel
public static Channel getChannel() throws Exception{
//创建一个连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("666.666.66.666");
factory.setUsername("admin");
factory.setPassword("123");
Connection connection = factory.newConnection();
return connection.createChannel();
}
}
消费者
import com.hzj.Utils.RabbitMqUtils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
public class Worker {
public static final String QUEUE_NAME = "Hello";
public static void main(String[] args) throws Exception {
Channel channel = RabbitMqUtils.getChannel();
DeliverCallback deliverCallback = (consumerTag, message) -> {
//将从通道的消息接收并输出
// message是消息全部, getBody 是仅仅得到消息体
System.out.println("接收到的消息是 : " + new String(message.getBody()));
};
CancelCallback cancelCallback = consumerTag ->{
System.out.println("消息消费被中断");
};
System.out.println("C2 进程等待中");
channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
}
}
生产者
import com.hzj.Utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Test02 {
public static final String QUEUE_NAME = "Hello";
public static void main(String[] args) throws Exception {
Channel channel = RabbitMqUtils.getChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false,null);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String massage = scanner.next();
channel.basicPublish("",QUEUE_NAME, null, massage.getBytes());
System.out.println("消息发送成功 : " + massage);
}
}
}
-> 同个类启动多个线程的方法
结果