rabbitmq原生java操作
1.一对一(一条消息只能被一个消费者消费) 基本操作(一个消息,一个消费者)
回复机制
自动回复-丢失消息,数据不是很重要
手动回复-数据重要
修改消费者,把自动改成手动
finalChannel.basicAck(deliveryTag,false);
多劳多得-每次只抓取一条,处理完成后手动回复
使用basicQos方法和prefetchCount = 1设置。 这告诉RabbitMQ一次不要向工作人员发送多于一条消息
channel.basicQos(1);
2.一对多
fanout:不做判断,所有消费者都接收消息
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
direct:满足routingkey才有
package com.sx._04_direct;
import com.rabbitmq.client.*;
import com.sx.util.ConnectionUtil;
import java.io.IOException;
public class Consumer3 {
private final static String QUEUE_NAME = "direct_exchange_queue_3";
private final static String EXCHANGE_NAME = "direct_exchange_test";
public static void main(String[] args) throws Exception {
Connection connection = null;
Channel channel = null; //上上层,所以访问不了
try
{
connection = ConnectionUtil.getConnection();
channel = connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
//队列绑定交换机
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"insert");
//定义消费方法
Channel finalChannel = channel; //匿名内部类只能访问上一层
DefaultConsumer consumer = new DefaultConsumer(finalChannel) {
/**
* 消费者接收消息调用此方法
* @param consumerTag 消费者的标签,在channel.basicConsume()去指定
* @param envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志
(收到消息失败后是否需要重新发送)
* @param properties
* @param body
*/
@Override
public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties properties,
byte[] body)
throws IOException {
//交换机
String exchange = envelope.getExchange();
//路由key
String routingKey = envelope.getRoutingKey();
//消息id
long deliveryTag = envelope.getDeliveryTag();
//消息内容
String msg = new String(body, "utf8");
System.out.println("3receive message.." + msg);
}
};
/**
* 监听队列:QUEUE 如果有消息来了,通过consumer来处理
* 参数明细
* 1、队列名称
* 2、是否自动回复,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置
为false则需要手动回复
* 3、消费消息的方法,消费者接收到消息后调用此方法
*/
channel.basicConsume(QUEUE_NAME, true, consumer);
//阻塞住,让他一直监听
System.in.read();
}catch (Exception e){
e.printStackTrace();
}finally {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
}
}
}
生产者
public class Producer {
//队列名称
private static final String QUEUE = "helloworld";
private final static String EXCHANGE_NAME = "direct_exchange_test";
public static void main(String[] args) throws Exception {
Connection connection = null;
Channel channel = null;
try {
//获取连接
connection = ConnectionUtil.getConnection();
//创建与Exchange的通道,每个连接可以创建多个通道,每个通道代表一个会话任务
channel = connection.createChannel();
String message = "helloworld小明" + System.currentTimeMillis();
//声明交换-fanout广播模式
channel.exchangeDeclare(EXCHANGE_NAME,"direct");
/**
* 消息发布方法
* param1:Exchange的名称,如果没有指定,则使用Default Exchange
* param2:routingKey(路由的key),消息的路由Key,是用于Exchange(交换机)将消息转发到指定的消息队列
* param3:消息包含的属性
* param4:消息体
*/
/**
* 这里没有指定交换机,消息将发送给默认交换机,每个队列也会绑定那个默认的交换机,但是不能显
示绑定或解除绑定
* 默认的交换机,routingKey等于队列名称
*/
/**
* 1 字符串
* ====fastjson======
* 2 对象--字符串 {}
* 3 集合对象-字符串[{}]
*/
channel.basicPublish(EXCHANGE_NAME, "delete", null, message.getBytes());
System.out.println("Send Message is:'" + message + "'");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
}
}
topic:routingkey可以有通配符
public class Consumer1 {
private final static String QUEUE_NAME = "direct_exchange_queue_1";
private final static String EXCHANGE_NAME = "topic_exchange_test";
public static void main(String[] args) throws Exception{
Connection connection=null;
Channel channel=null;
try{
connection=ConnectionUtil.getConnection();
channel=connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
//队列绑定交换机
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"insert");
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"delete");
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"update");
//定义消费方法
Channel finalChannel=channel;//匿名内部类只能访问上一层
DefaultConsumer consumer=new DefaultConsumer(finalChannel){
/**
* 消费者接收消息调用此方法
* @param consumerTag 消费者的标签,在channel.basicConsume()去指定
* @param envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志
(收到消息失败后是否需要重新发送)
* @param properties
* @param body
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//交换机
String exchange=envelope.getExchange();
//路由key
String routingKey=envelope.getRoutingKey();
//消息id
long deliveryTag=envelope.getDeliveryTag();
//消息内容
String msg=new String(body,"utf8");
System.out.println("1receive message.."+msg);
}
};
/**
* 监听队列:QUEUE 如果有消息来了,通过consumer来处理
* 参数明细
* 1、队列名称
* 2、是否自动回复,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置
为false则需要手动回复
* 3、消费消息的方法,消费者接收到消息后调用此方法
*/
channel.basicConsume(QUEUE_NAME,true,consumer);
//阻塞住,让他一直监听
System.in.read();
}catch (Exception e){
e.printStackTrace();
}finally {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
}
}
生产者
public class Producer {
//队列名称
private static final String QUEUE = "helloworld";
private final static String EXCHANGE_NAME = "topic_exchange_test";
public static void main(String[] args) throws Exception {
Connection connection = null;
Channel channel = null;
try {
//获取连接
connection = ConnectionUtil.getConnection();
//创建与Exchange的通道,每个连接可以创建多个通道,每个通道代表一个会话任务
channel = connection.createChannel();
String message = "helloworld小明" + System.currentTimeMillis();
//声明交换-fanout广播模式
channel.exchangeDeclare(EXCHANGE_NAME,"topic",false);
/**
* 消息发布方法
* param1:Exchange的名称,如果没有指定,则使用Default Exchange
* param2:routingKey(路由的key),消息的路由Key,是用于Exchange(交换机)将消息转发到指定的消息队列
* param3:消息包含的属性
* param4:消息体
*/
/**
* 这里没有指定交换机,消息将发送给默认交换机,每个队列也会绑定那个默认的交换机,但是不能显
示绑定或解除绑定
* 默认的交换机,routingKey等于队列名称
*/
/**
* 1 字符串
* ====fastjson======
* 2 对象--字符串 {}
* 3 集合对象-字符串[{}]
*/
channel.basicPublish(EXCHANGE_NAME, "delete", null, message.getBytes());
System.out.println("Send Message is:'" + message + "'");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
}
}
header:Map
要将消息持久化,前提是:队列、Exchange都持久化
springboot rabbitmq
1.导入jar
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--spirngboot集成rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配置yml
server:
port: 44000
spring:
application:
name: test‐rabbitmq‐producer
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtualHost: /
配置类
@Configuration
public class RabbitmqConfig {
public static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
public static final String QUEUE_INFORM_SMS = "queue_inform_sms";
public static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";
/**
* 交换机配置
* ExchangeBuilder提供了fanout、direct、topic、header交换机类型的配置
*
* @return the exchange
*/
@Bean(EXCHANGE_TOPICS_INFORM)
public Exchange EXCHANGE_TOPICS_INFORM() {
//durable(true)持久化,消息队列重启后交换机仍然存在
return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_INFORM).durable(true).build();
}
//声明队列
@Bean(QUEUE_INFORM_SMS)
public Queue QUEUE_INFORM_SMS() {
Queue queue = new Queue(QUEUE_INFORM_SMS);
return queue;
}
//声明队列
@Bean(QUEUE_INFORM_EMAIL)
public Queue QUEUE_INFORM_EMAIL() {
Queue queue = new Queue(QUEUE_INFORM_EMAIL);
return queue;
}
/**
* channel.queueBind(INFORM_QUEUE_SMS,"inform_exchange_topic","inform.#.sms.#");
* 绑定队列到交换机 .
*
* @param queue the queue
* @param exchange the exchange
* @return the binding
*/
@Bean
public Binding BINDING_QUEUE_INFORM_SMS(@Qualifier(QUEUE_INFORM_SMS) Queue queue,
@Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("inform.#.sms.#").noargs();
}
@Bean
public Binding BINDING_QUEUE_INFORM_EMAIL(@Qualifier(QUEUE_INFORM_EMAIL) Queue queue,
@Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("inform.#.email.#").noargs();
}
}
入口类
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
生产者
@SpringBootTest(classes = App.class)
@RunWith(SpringRunner.class)
public class Producer05_topics_springboot {
@Autowired
RabbitTemplate rabbitTemplate;
@Test
public void testSendByTopics() {
for (int i = 0; i < 5; i++) {
String message = "sms email inform to user" + i;
rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPICS_INFORM, "inform.sms.email", message);
System.out.println("Send Message is:'" + message + "'");
}
}
}
消费端
@Component
public class ReceiveHandler {
//监听email队列
@RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_EMAIL})
public void receive_email(String msg, Message message, Channel channel) {
System.out.println(msg);
}
//监听sms队列
@RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_SMS})
public void receive_sms(String msg, Message message, Channel channel) {
System.out.println(msg);
}
}