rabbitMq相关配置示例----java

226 阅读2分钟
创建一个交换机 两个队列 ,并设置根据不同的路由key向不同的消息队列发送消息
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author atguigu-mqx
 */
@Configuration
public class DeadLetterMqConfig {
    //  定义一些变量:
    public static final String exchange_dead = "exchange.dead";
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";

    //  定义一个交换机
    @Bean
    public DirectExchange exchange(){
        //  创建交换机
        return new DirectExchange(exchange_dead,true,false);
    }
    //  创建一个队列
    @Bean
    public Queue queue1(){
        //  延迟队列:
        HashMap<String, Object> map = new HashMap<>();
        //  设置队列2 的绑定!
        map.put("x-dead-letter-exchange",exchange_dead);
        //  使用routing key 2 绑定到队列2上!
        map.put("x-dead-letter-routing-key",routing_dead_2);
        //  设置消息的过期时间
        map.put("x-message-ttl",10000);
        return new Queue(queue_dead_1,true,false,false,map);
    }

    //  设置绑定关系!
    @Bean
    public Binding binding1(){
        //  返回绑定关系!
        return BindingBuilder.bind(queue1()).to(exchange()).with(routing_dead_1);
    }

    //  设置队列2
    @Bean
    public Queue queue2(){
        return new Queue(queue_dead_2,true,false,false);
    }

    //  设置绑定关系!
    @Bean
    public Binding binding2(){
        //  返回绑定关系!
        return BindingBuilder.bind(queue2()).to(exchange()).with(routing_dead_2);
    }
一个交换机一个消息队列 一个绑定关系
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author atguigu-mqx
 */
@Configuration
public class DelayedMqConfig {

    //  一个交换机一个队列一个绑定关系!
    public static final String exchange_delay = "exchange.delay";
    public static final String routing_delay = "routing.delay";
    public static final String queue_delay_1 = "queue.delay.1";

    //  定义交换机
    @Bean
    public CustomExchange delayExchange(){
        //  设置参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("x-delayed-type","direct");
        //  第二个参数固定值!
        return new CustomExchange(exchange_delay,"x-delayed-message",true,false,map);
    }
    //  定义队列
    @Bean
    public Queue delayQueue(){
        //  返回队列
        return new Queue(queue_delay_1,true,false,false);
    }
    //  定义绑定关系
    @Bean
    public Binding delayBinding(){
        //  返回绑定关系!
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(routing_delay).noargs();
    }
}
消息监听和消息确认

/**
 * @author atguigu-mqx
 */
@Component
public class ConfirmReceiver {

    //  监听消息:
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.confirm",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "exchange.confirm"),
            key = {"routing.confirm"}
    ))
    public void getMsg(String msg, Message message, Channel channel){
        System.out.println("接收到的消息:"+msg);

        System.out.println("接收到的消息 message.getBody() :"+new String(message.getBody()));

        //  确认消息: 第一个参数:就是标签  第二个参数表示:是否批量确认!
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听消息!
    @SneakyThrows
    @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    public void queue2(String msg,Message message,Channel channel){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("接收到的消息:\t"+msg);
        System.out.println("接收到的时间:\t"+simpleDateFormat.format(new Date()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听消息!
    @SneakyThrows
    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    public void queue3(String msg,Message message,Channel channel){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("接收到的消息:\t"+msg);
        System.out.println("接收到的时间:\t"+simpleDateFormat.format(new Date()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
消息确认的配置
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author atguigu-mqx
 * 这个类 是通知我们向交换机和消息队列发送消息是否成功
 */
@Component
public class MQProducerAckConfig implements RabbitTemplate.ReturnCallback, RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //  编写一个初始化方法!
    @PostConstruct
    public void init(){
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setConfirmCallback(this);
    }
    /**
     * 表示判断消息是否发送到交换机!
     * @param correlationData
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        //  判断
        if (ack){
            System.out.println("发送成功....");
        }else {
            System.out.println("发送失败....");
        }
    }

    /**
     * 判断当前消息是否能够到队列中! 如果到队列中了,则这个方法不执行! 如果没有到队列中,则方法执行!
     * @param message
     * @param replyCode
     * @param replyText
     * @param exchange
     * @param routingKey
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
//        可以通过判断方式来确切指定哪些是基于延迟插件的交换机路由键 ! 则 return!
//        if ("exchange.delay".equals(exchange) && "routing.delay".equals(routingKey)){
//            return;
//        }

        System.out.println("消息主体: " + new String(message.getBody()));
        System.out.println("应答码: " + replyCode);
        System.out.println("描述:" + replyText);
        System.out.println("消息使用的交换器 exchange : " + exchange);
        System.out.println("消息使用的路由键 routing : " + routingKey);
    }
}
向消息队列发送消息
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author atguigu-mqx
 */
@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    //  编写发送消息的方法  
    public Boolean sendMessage(String exchange, String routingKey, Object message){
        //  发送消息
        this.rabbitTemplate.convertAndSend(exchange,routingKey,message);
        //  返回值
        return true;
    }
}