消息队列解决了什么问题java
# docker run --name rabbitmq -tid -p 5672:5672 -p 15672:15672 -p 25672:25672 rabbitmq
# docker exec -it 容器号 /bin/bash
# rabbitmqctl add_user [user_name] [pwd]
# rabbitmqctl list_users
# rabbitmqctl set_permissions -p "/" [user_name] ".*" ".*" ".*" # rabbitmqctl list_permissions -p /
# rabbitmqctl set_user_tags asdf administrator
# rabbitmqctl delete_user guest
# rabbitmq-plugins enable rabbitmq_management
# http://IP:15672
Java操做RabbitMQweb
<dependencies> <!-- 引入队列依赖 --> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>4.0.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.10</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> </dependencies>
public class connectionUtil { public static Connection getConnection() throws IOException, TimeoutException { //定义连接工厂 ConnectionFactory factory = new ConnectionFactory(); //设置服务地址[运行rabbitMQ的地址] factory.setHost("192.168.168.130"); //AMQ的端口号 factory.setPort(5672); //vHost factory.setVirtualHost("lgz"); factory.setUsername("lgz"); factory.setPassword("pwd123456"); return factory.newConnection(); } }
//测试发送信息 public class ProducerSend { private static final String QUEUE_NAME="test_simple_queue"; public static void main(String[] args) throws IOException, TimeoutException { System.out.println("cs"); //获取连接 Connection connection = connectionUtil.getConnection(); //从连接中获取通道 Channel channel = connection.createChannel(); //队列声明 channel.queueDeclare(QUEUE_NAME,false,false,false,null); String msg="hello simple"; channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); System.out.println("test success"); channel.close(); connection.close(); } }
public class comsumerGain { private static final String QUE_NAME="test_simple_queue"; public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection connection = connectionUtil.getConnection(); //建立通道 Channel channel = connection.createChannel(); //定义消费者 DefaultConsumer consumer = new DefaultConsumer(channel) { //获取到达的消息 @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg = new String(body, "utf-8"); System.out.println(msg); } }; //监听队列 channel.basicConsume(QUE_NAME,true,consumer); } }
public class WorkQueue { public static final String QUEUE_NAME="work_queue"; public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //建立链接 Connection connection = connectionUtil.getConnection(); //获取channel连接 Channel channel = connection.createChannel(); // channel.queueDeclare(QUEUE_NAME,false,false,false,null); for (int i = 0; i <50 ; i++) { String msg="No"+i; System.out.println(msg); channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); Thread.sleep(i*20); } channel.close(); connection.close(); } }
public class WorkRecv { private final static String QUEUE_NAME="work_queue"; public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection connection = connectionUtil.getConnection(); //获取channel 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 { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("receive"+msg); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("结束"); } } }; channel.basicConsume(QUEUE_NAME,true,defaultConsumer); }
public class WorkRecv { private final static String QUEUE_NAME="work_queue"; public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection connection = connectionUtil.getConnection(); //获取channel 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 { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("receive"+msg); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("结束"); } } }; channel.basicConsume(QUEUE_NAME,true,defaultConsumer); } }
public class WorkQueue { public static final String QUEUE_NAME="work_queue"; public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //建立链接 Connection connection = connectionUtil.getConnection(); //获取channel连接 Channel channel = connection.createChannel(); // channel.queueDeclare(QUEUE_NAME,false,false,false,null); /* * 每一个消费者发送确认消息以前,消息队列不发送下一个消息到消费者。【一次只处理一个消息】 * */ int prefetchCount=1; channel.basicQos(prefetchCount); for (int i = 0; i <50 ; i++) { String msg="No"+i; System.out.println(msg); channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); Thread.sleep(i*20); } channel.close(); connection.close(); } }
public class WorkRecv { private final static String QUEUE_NAME="work_queue"; public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection connection = connectionUtil.getConnection(); //获取channel final Channel channel = connection.createChannel(); //声明队列 channel.queueDeclare(QUEUE_NAME,false,false,false,null); channel.basicQos(1); //一次只分发一个 //定义一个消费者 DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { //消息触发 @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("receive"+msg); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("结束"); channel.basicAck(envelope.getDeliveryTag(),false); } } }; channel.basicConsume(QUEUE_NAME,false,defaultConsumer); } }
public class WorkReceive { private final static String QUEUE_NAME="work_queue"; public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection connection = connectionUtil.getConnection(); //获取channel final Channel channel = connection.createChannel(); //声明队列 channel.queueDeclare(QUEUE_NAME,false,false,false,null); //保证每次只分发一个 channel.basicQos(1); //定义一个消费者 DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { //消息触发 @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("receive"+msg); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("【start】:"); //手动回执一个消息 channel.basicAck(envelope.getDeliveryTag(),false); } } }; channel.basicConsume(QUEUE_NAME,false,defaultConsumer); } }
若是这种状况下,杀死正在执行的消费者,就会形成正在处理的信息丢失。算法
//声明队列 channel.queueDeclare(QUEUE_NAME,[durable]false,false,false,null); //durable:持久化,
将程序中的durable的false改称为true,也是不能够的。由于定义的QUEUE_NAME表明这个queue是未持久化的,rabbitmq不许从新定义一个已存在的队列spring
public class Send { public static final String EXCHANGE_NAME="test_exchange_fanout"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); //声明交换机 channel.exchangeDeclare(EXCHANGE_NAME,"fanout");//分发 String msg="hello_exchange"; channel.basicPublish(EXCHANGE_NAME,"",null,msg.getBytes()); System.out.println("send:"+msg); channel.close(); connection.close(); } }
public class Receive1 { public static final String QUEUE_NAME="test_queue_exchange"; public static final String EXCHANGE_NAME="test_exchange_fanout"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); //绑定队列到交换机 channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,""); channel.basicQos(1);//保证每次只能分发一个 DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("Receive1"+msg); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("[ok]"); channel.basicAck(envelope.getDeliveryTag(),false); } } }; boolean autoAck=false; channel.basicConsume(QUEUE_NAME,autoAck,defaultConsumer); } }
public class Receive2{ public static final String QUEUE_NAME="email_queue_exchange"; public static final String EXCHANGE_NAME="test_exchange_fanout"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); //绑定队列到交换机 channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,""); channel.basicQos(1);//保证每次只能分发一个 DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("Receive2"+msg); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("[ok2]"); channel.basicAck(envelope.getDeliveryTag(),false); } } }; boolean autoAck=false; channel.basicConsume(QUEUE_NAME,autoAck,defaultConsumer); } }
一方面接收生产者的消息,另外一方面向队列发送消息sql
Fanout(不处理路由键)docker
Direct(处理路由键)api
public class Send { public static final String EXCHANGE_NAME="test_exchange_direct"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); //声明交换机 channel.exchangeDeclare(EXCHANGE_NAME,"direct"); String msg=new String("Hello direct"); String routingKey="warning"; channel.basicPublish(EXCHANGE_NAME,routingKey,null,msg.getBytes()); System.out.println("send"+msg); channel.close(); connection.close(); } }
public class Receive1 { public static final String EXCHANGE_NAME="test_exchange_direct"; public static final String QUEUE_NAME="queue_direct_1"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); final Channel channel = connection.createChannel(); // channel.queueDeclare(QUEUE_NAME,false,false,false,null); channel.basicQos(1); channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"error"); //定义一个消费者 DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("[done]"+msg); channel.basicAck(envelope.getDeliveryTag(),false); } } }; boolean autoAck=false;//自动应答false channel.basicConsume(QUEUE_NAME,autoAck,consumer); } }
public class Receive2 { public static final String EXCHANGE_NAME="test_exchange_direct"; public static final String QUEUE_NAME="queue_direct_1"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); final Channel channel = connection.createChannel(); // channel.queueDeclare(QUEUE_NAME,false,false,false,null); channel.basicQos(1); channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"error"); channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"warning"); channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"info"); //定义一个消费者 DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("[done]"+msg); channel.basicAck(envelope.getDeliveryTag(),false); } } }; boolean autoAck=false;//自动应答false channel.basicConsume(QUEUE_NAME,autoAck,consumer); } }
相似于sql中的模糊查询,springboot
将路由键routing key和某个模式盘匹配bash
public class Send { private static final String EXCHANGE_NAME="test_exchange_topic"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME,"topic"); String msg="商品"; channel.basicPublish(EXCHANGE_NAME,"goods.delete",null,msg.getBytes()); System.out.println("---send"+msg); channel.close(); connection.close(); } }
public class Receive1 { public static final String QUEUE_NAME="test_queue_topic_1"; private static final String EXCHANGE_NAME="test_exchange_topic"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); //绑定队列到交换机 channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"goods.add"); channel.basicQos(1);//保证每次只能分发一个 DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("Receive1"+msg); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("[ok]"); channel.basicAck(envelope.getDeliveryTag(),false); } } }; boolean autoAck=false; channel.basicConsume(QUEUE_NAME,autoAck,defaultConsumer); } }
public class Receive2 { public static final String QUEUE_NAME="test_queue_topic_1=2"; private static final String EXCHANGE_NAME="test_exchange_topic"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); //绑定队列到交换机 channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"goods.#"); channel.basicQos(1);//保证每次只能分发一个 DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg=new String(body,"utf-8"); System.out.println("Receive1"+msg); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("[ok]"); channel.basicAck(envelope.getDeliveryTag(),false); } } }; boolean autoAck=false; channel.basicConsume(QUEUE_NAME,autoAck,defaultConsumer); } }
在MQ中能够经过持久化数据解决rabbitmq服务器异常的数据丢失问题服务器
生产者将消息发送出去之后,如何知道消息到底有没有到达rabbitmq服务器?
txSelect :用户将当前channel设置成transaction模式
txCommit:用于提交事务
txRollback:回滚事务
public class TxSend { private static final String QUEUE_NAME="tx_queue"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); String msg="hello autoCommit"; channel.queueDeclare(QUEUE_NAME,false,false,false,null); try { channel.txSelect(); channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); channel.txCommit(); int i=1/0; System.out.println(msg); } catch (IOException e) { channel.txRollback(); System.out.println("error"); e.printStackTrace(); } channel.close(); connection.close(); } }
public class TxReceive1 { private static final String QUEUE_NAME="tx_queue"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); channel.basicConsume(QUEUE_NAME,true,new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); System.out.println("receive"+new String(body,"utf-8")); } }); } }
public class Send1 { private static final String QUEUE_NAME="tx_queue"; public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); //设置为confirm模式 channel.confirmSelect(); String msg="confirm_text"; channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); if (!channel.waitForConfirms()){ System.out.println("send message failed"); }else { System.out.println("success"); } channel.close(); connection.close(); } }
public class SendMore { private static final String QUEUE_NAME="confirm_queue"; public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); //设置为confirm模式 channel.confirmSelect(); String msg="confirm_text"; channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); //主要进行遍历发送,串行的【发送完以后在进行确认】 for (int i = 0; i <10 ; i++) { channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); } if (!channel.waitForConfirms()){ System.out.println("send message failed"); }else { System.out.println("success"); } channel.close(); connection.close(); } }
//绑定channel与消息队列 //参数一:队列名称【若是不存在该队列,则自动建立】 //参数二:durable【是否要进行持久化】 //参数三:exclusive【是否独占队列】 //参数四:是否在消费完成以后是否要当即删除队列【true:自动删除】【false:不自动删除】 //参数五:额外参数 channel.QueueDeclare(name, durable, autoDelete, exclusive, noWait, args); channel.queueDeclare("helloWorld",false,false,false,null);
//发布消息 /* * 参数1:【exchange】交换机名称 * 参数2:【routingKey】队列名称 * 参数3:【props】传递消息的额外设置 * 参数4:传递消息的具体内容【byte类型】 * * */ channel.basicPublish("","helloWorld",null,"hello rabbitMQ".getBytes());
//消费信息 /* * 参数一:队列名称 * 参数二:开启消息的自动确认机制 * 参数三:消费时的回调接口 * */ channel.basicConsume("helloWorld",true,consumer);
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.2.6.RELEASE</version> </dependency>
spring: application: name: rabbit-springboot rabbitmq: host: 192.168.168.130 port: 5672 virtual-host: / username: lgz password: pwd123456
@Autowired private RabbitTemplate rabbitTemplate; @Test void contextLoads() { rabbitTemplate.convertAndSend("hello","helloWorld"); System.out.println(1); }
@SpringBootTest class BootRabbitmqApplicationTests { @Autowired private RabbitTemplate rabbitTemplate; @Test void contextLoads() { rabbitTemplate.convertAndSend("hello","helloWorld"); System.out.println(1); } @Test public void testWork(){ for (int i = 0; i <5 ; i++) { rabbitTemplate.convertAndSend("work","work模型"); } } @Test public void testFanout(){ rabbitTemplate.convertAndSend("logs","","Fanout model"); } @Test public void testRouting(){ rabbitTemplate.convertAndSend("directs","info","info_key_routing_information"); } @Test public void testTopic(){ rabbitTemplate.convertAndSend("topics","user.save","user.save exchange"); } }
@RabbitListener(bindings = { @QueueBinding( value = @Queue, exchange = @Exchange(type = "topic",name = "topics"), key = {"product.save","product.*"} ) }) public void receive(String msg){ System.out.println("consumer1"+msg); } @RabbitListener(bindings = { @QueueBinding( value = @Queue, exchange = @Exchange(type = "topic",name = "topics"), key = {"user.save","user.*"} ) }) public void receive2(String msg){ System.out.println("consumer2"+msg); }
@RabbitListener(bindings = { @QueueBinding( value = @Queue, exchange = @Exchange(value = "directs",type = "direct"), key = {"info","error"} ) }) public void receive1(String msg){ System.out.println(msg); }
@RabbitListener(queuesToDeclare = @Queue("work")) public void receive(String message){ System.out.println("message:["+message+"]"); }
@RabbitListener(bindings = { @QueueBinding( value = @Queue, //建立临时队列 exchange =@Exchange(value = "logs", type = "fanout") //绑定的交换机 ) }) public void receive1(String msg){ System.out.println("["+msg+"]"); }
@Component @RabbitListener(queuesToDeclare = @Queue("hello")) public class Hello { @RabbitHandler public void receive1(String message){ System.out.println("message"+message); } }