生产者:
1.创建连接;
2.创建通道;
3.创建队列;
4.发送消息;
5.关闭连接;
public class producter { public static void main(String[] args) throws Exception { //1.创建链接 //2.创建通道 Channel channel = MyUtil.getConnectionFactory(); //3.创建交换机 channel.exchangeDeclare("redirt", BuiltinExchangeType.DIRECT, true); //4.发送消息 for(int i = 0;i<=10;i++){ String msg = "定向模型发送成功 "; channel.basicPublish("redirt","redirtKey",null,msg.getBytes()); System.out.println("定向模型创建成功"); } //5.关闭连接 channel.close(); } }
消费者:
1.创建连接;
2.创建通道;
3.监听队列;
4.处理业务;
5.手动ACK;
public class Consumer1 { public static void main(String[] args){ //1.创建连接 //2.创建通道 Channel channel = MyUtil.getConnectionFactory(); //3.创建队列 try { channel.queueDeclare("queueDirect", true, false, false, null); //4.绑定交换机; channel.queueBind("queueDirect","redirt","redirtKey"); //5.监听队列 channel.basicConsume("queueDirect",new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //6.处理业务 System.out.println(new String(body)+1); //7.手动ack channel.basicAck(envelope.getDeliveryTag(), false); } }); } catch (IOException e) { e.printStackTrace(); } }public class Consumer2 { public static void main(String[] args) throws IOException { //1.创建连接 //2.创建通道 Channel channel = MyUtil.getConnectionFactory(); //3.创建队列 channel.queueDeclare("yidaqi777", true, false, false, null); //4.绑定交换机】 channel.queueBind("yidaqi777","redirt","111"); //5.监听队列 channel.basicConsume("yidaqi777",new DefaultConsumer(channel) { //6.处理业务 @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println(new String(body)+2); //7.手动ack channel.basicAck(envelope.getDeliveryTag(),false); } }); }
RabbitMQ代码端端口号:5672;
RabbitMQ服务流程
服务板块.服务主要分为三大板块:<生产者>~<RabbitMQ服务端>-<消费者> ;
1.生产者创建连接,并开启连接通道;
2.生产者发送消息,并创建交换机;
3.生产者发送的消息发送到交换机,再通过交换机分发到绑定的队列;(交换机不储存代码,只负责分发代码);
4.消费者通过创建队列,绑定相应的交换机;
5.消费者再通过监听队列时时刻刻监听队列的消息;
6.消费者再处理业务;
7.最后手动关闭ack;
那么多MQ消息中间件,为什么用RabbitMQ?
原因:1基础AMQP协议;
2.社区活跃,文档完善;
3.比较适用于中小型企业开发;
4.springBoot已默认集成RabbitMQ;
5.RabbitMQ由erlang语言开发,支持高并发,性能好;
五种模型:
1.helloWorld:队列由生产者创建,无交换机产生,生产者发送 消息,消费者通过监听接收消息;
2.workQueue:队列由生产者创建,无交换机产生,讲究能者多劳,用
channel.basicQos(1)添加权重;
3.广播模型:队列由消费者创建,生产者创建交换机,不用设置routingkey,交换机类型改为direct,生产者产生的消息,所有的消费者都监听得到;
4.定向模型:队列由消费者创建,生产者创建交换机,消费者通过发布消息的routingkey与交换机的key匹配,来监听消息,交换机的routding与发布消息不一致的则监听不到消息;
5.通配模型:#:表示一个或者多个
*:只表示一个; 根据routing来匹配;