Rabbit MQ java客户端访问以及springboot集成
java访问rabbit MQ及相关参数详解
1、添加依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
</dependency>
2、创建消费者类及参数说明
消费者的工作流程:
- 初始化 rabbitMq : ConnectionFactory
- 建立connection连接
- 创建channel消息通道
- 声明交换机
- 声明队列
- 绑定队列和交换机
- 创建消费者
- 开始获取消息
import com.rabbitmq.client.*;
import java.io.IOException;
/**
* @auther rabbit-mq 消费者
* @create xxxx/xx/xx
*/
public class RabbitConsumer {
private final static String EXCHANGE_NAME = "FIRST_EXCHANGE";
private final static String QUEUE_NAME = "FIRST_QUEUE";
public static void main(String[] args) throws Exception {
// 初始化 rabbitMq : ConnectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("117.78.8.247"); // ip
connectionFactory.setPort(5672); // 端口
connectionFactory.setUsername("admin"); // username
connectionFactory.setPassword("admin"); // password
connectionFactory.setVirtualHost("/"); // 虚拟机
// 建立连接
Connection connection = connectionFactory.newConnection();
// 创建消息通道
Channel channel = connection.createChannel();
/**
* 声明交换机
* String exchange 交换机名称
* BuiltinExchangeType type 交换机类型:DIRECT("direct")直连交换机,FANOUT("fanout")广播交换机,TOPIC("topic")主题交换机,HEADERS("headers");
* boolean durable 是否持久化,durable设置为true表示持久化,反之是非持久化,持久化的可以将交换器存盘,在服务器重启的时候不会丢失信息.
* boolean autoDelete 是否自动删除,设置为TRUE则表是自动删除,自删除的前提是至少有一个队列或者交换器与这交换器绑定,之后所有与这个
* 交换器绑定的队列或者交换器都与此解绑,一般都设置为fase
* boolean internal 是否内置,如果设置 为true,则表示是内置的交换器,客户端程序无法直接发送消息到这个交换器中,只能通过交换器路由到交换器的方式
* Map<String, Object> arguments
*/
channel.exchangeDeclare(EXCHANGE_NAME,BuiltinExchangeType.DIRECT,false,false,false,null);
/** 声明队列
* String queue 队列的名称
* boolean durable 是否是持久化的,队列的声明默认是存放到内存中的,如果rabbitmq重启会丢失,
* 如果想重启之后还存在就要使队列持久化,保存到Erlang自带的Mnesia数据库中,当rabbitmq重启之后会读取该数据库
* boolean exclusive 是否排外。排外有两个特征:
* a、当连接关闭时connection.close()该队列是否会自动删除
* b、该队列是否是私有的private,其他通道channel是不能访问的,如果强制访问会报异常:
* com.rabbitmq.client.ShutdownSignalException: channel error; protocol method:
* #method<channel.close>(reply-code=405,reply-text=RESOURCE_LOCKED -
* cannot obtain exclusive access to locked queue 'queue_name' in vhost '/', class-id=50, method-id=20)
* 一般等于true的话用于一个队列只能有一个消费者来消费的场景
* boolean autoDelete 是否自动删除,当前最后一个consumer断开之后,autodelete被触发
* Map<String, Object> arguments 此参数可选,可配置的相关属性为:
* a、x-message-ttl - TTL:设置队列中的所有消息的生存周期(统一为整个队列的所有消息设置生命周期),
* 也可以在发布消息的时候单独为某个消息指定剩余生存时间,单位毫秒。
* 例:{" x-message-ttl",1000*10} 表明此队列的msg只能存活10秒
* b、x-expires:当队列在指定的时间没有被访问(consume, basicGet, queueDeclare…)就会被删除.
* 注意这里是删除队列.不是队列中的消息
* c、x-max-length:限定队列的消息的最大值长度,超过指定长度将会把最早的几条删除掉
* d、x-max-length-bytes:限定队列最大占用的空间大小, 一般受限于内存、磁盘的大小
* e、x-dead-letter-exchange:当队列消息长度大于最大长度、或者过期的等,
* 将从队列中删除的消息推送到指定的交换机中去而不是丢弃掉(可用于做消息的延时发送)
* f、x-dead-letter-routing-key:将删除的消息推送到指定交换机的指定路由键的队列中去
* g、x-max-priority:优先级队列,声明队列时先定义最大优先级值(定义最大值一般不要太大).
* 在发布消息的时候指定该消息的优先级, 优先级更高(数值更大的)的消息先被消费
* h、x-queue-mode=lazy:先将消息保存到磁盘上,不放在内存中,当消费者开始消费的时候才加载到内存中
*/
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
/**
* 绑定队列和交换机
* String queueName 队列名称
* String exchangeName 交换机名称
* String bindingKey
*/
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"rabbit.key");
// 创建消费者
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body,"utf-8");
System.out.println("this is the msg : "+msg);
}
};
// 开始获取消息
channel.basicConsume(QUEUE_NAME,consumer);
}
}
3、创建生产者类及参数说明
生产者的工作流程:
- 初始化 rabbitMq : ConnectionFactory
- 建立connection连接
- 创建channel消息通道
- 编辑要发送的消息
- 发送消息
import com.rabbitmq.client.*;
/**
* @auther rabbit-mq 生产者
* @create xxxx/xx/xx
*/
public class RabbitProducer {
private final static String EXCHANGE_NAME = "FIRST_EXCHANGE";
private final static String QUEUE_NAME = "FIRST_QUEUE";
public static void main(String[] args) throws Exception {
// 初始化 rabbitMq : ConnectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("117.78.8.247"); // ip
connectionFactory.setPort(5672); // 端口
connectionFactory.setUsername("admin"); // username
connectionFactory.setPassword("admin"); // password
connectionFactory.setVirtualHost("/"); // 虚拟机
// 建立连接
Connection connection = connectionFactory.newConnection();
// 创建消息通道
Channel channel = connection.createChannel();
// 要发送的消息
String msg = "hello rabbit MQ";
// 发送消息(发送到默认交换机AMQP Default,Direct)
// String exchange 指定发送的交换机
// String routingKey 路由键
// BasicProperties props
/**
* public static class BasicProperties extends AMQBasicProperties {
* private String contentType; // 消息类型(text/plain)
* private String contentEncoding; // 编码
* private Map<String, Object> headers; // 自定义属性
* private Integer deliveryMode; // 值为2时,表明消息持久化
* private Integer priority;
* private String correlationId;
* private String replyTo;
* private String expiration; // TTL
* private String messageId;
* private Date timestamp;
* private String type;
* private String userId;
* private String appId;
* private String clusterId;
*/
// Map<String,Object> headers = new HashMap<>();
// headers.put("key1","value1");
// headers.put("key2","value2");
// BasicProperties props = new AMQP.BasicProperties().builder()
// .deliveryMode(2)
// .contentEncoding("utf-8")
// .expiration("10000")
// .headers(headers)
// .build();
// byte[] body 发送的消息
channel.basicPublish(EXCHANGE_NAME,"rabbit.key",null,msg.getBytes());
System.out.println("the msg is send : "+msg);
}
}
springboot集成rabbit MQ
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
2、添加配置类
配置类的工作内容:
- 开启RabbitMQ配置:
@EnableRabbit
- 声明交换机
- 声明队列
- 声明交换机和队列的绑定关系
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @auther RabbitConfig
* @create xxxx/xx/xx
*/
@Configuration
@EnableRabbit // 开启rabbit MQ
public class RabbitConfig {
private final static String EXCHANGE_NAME = "DIRECT_EXCHANGE"; // 交换机名称
private final static String QUEUE_NAME = "FIRST_QUEUE"; // 队列名称
// 声明交换机
@Bean
public DirectExchange directExchange(){
return new DirectExchange(EXCHANGE_NAME);
}
// 声明队列
@Bean
public Queue firstQueue(){
return new Queue(QUEUE_NAME);
}
// 声明交换机和队列的绑定关系
@Bean
public Binding binding(@Qualifier("firstQueue") Queue firstQueue,
@Qualifier("directExchange") DirectExchange directExchange){
return BindingBuilder.bind(firstQueue).to(directExchange).with("rabbit_key");
}
}
3、创建消费者
消费者的工作内容:
- 监听Rabbit MQ的队列:
@RabbitListener(queues = "FIRST_QUEUE")
- 接收消息并进行后置处理
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @auther springboot集成rabbitmq - 消费者
* @create xxxx/xx/xx
*/
@Component
@RabbitListener(queues = "FIRST_QUEUE")
public class ConsumerServer {
/**
* 消费者收到队列中的消息,并进行后置处理
* @param msg
*/
@RabbitHandler
public void process(String msg){
System.out.println("consumer this is the springboot msg");
}
}
4、创建生产者
生产者的工作内容:
- 注入Rabbit MQ操作对象:
RabbitTemplate
或者AmqpTemplate
- 发送消息
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @auther springboot集成rabbitmq - 生产者
* @create xxxx/xx/xx
*/
@Component
public class ProducerServer {
@Autowired
RabbitTemplate rabbitTemplate;
/**
* 发送消息
*/
public void sendMsg(){
String msg = "producer send a springboot msg";
rabbitTemplate.convertAndSend("DIRECT_EXCHANGE","rabbit_key",msg);
}
}
nt
public class ProducerServer {
@Autowired
RabbitTemplate rabbitTemplate;
/**
* 发送消息
*/
public void sendMsg(){
String msg = "producer send a springboot msg";
rabbitTemplate.convertAndSend("DIRECT_EXCHANGE","rabbit_key",msg);
}
}