怎样使用RabbitMQ传递对象

1.首先我们需要配置rabbit所需要的依赖

org.springframework.boot
spring-boot-starter-amqp

2.在springboot中的application.yml里面配置下面的这些数据
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
publisher-confirms: true # 消息发送到交换机确认机制,是否确认回调
publisher-returns: true
devtools:
restart:
enabled: false
server:
port: 8088

3.消息交换机配置 可以配置多个
public class ExchangeConfig {

/**
 *   1.定义direct exchange,绑定queueTest
 *   2.durable="true" rabbitmq重启的时候不需要创建新的交换机
 *   3.direct交换器相对来说比较简单,匹配规则为:如果路由键匹配,消息就被投送到相关的队列
 *     fanout交换器中没有路由键的概念,他会把消息发送到所有绑定在此交换器上面的队列中。
 *     topic交换器你采用模糊匹配路由键的原则进行转发消息到队列中
 */
@Bean
public DirectExchange directExchange(){
    DirectExchange directExchange = new DirectExchange(RabbitMqConfig.EXCHANGE,true,false);
    return directExchange;
}

下面是配置多个队列
public class QueueConfig {

@Bean
public Queue firstQueue() {
    /**
     durable="true" 持久化 rabbitmq重启的时候不需要创建新的队列
     auto-delete 表示消息队列没有在使用时将被自动删除 默认是false
     exclusive  表示该消息队列是否只在当前connection生效,默认是false
     */
    return new Queue(RabbitMqConfig.QUEUE_NAME1,true,false,false);
}

@Bean
public Queue secondQueue() {
    return new Queue(RabbitMqConfig.QUEUE_NAME2,true,false,false);
}

}
下面主要是队列、交换机和工厂的连接
public class RabbitMqConfig {

/** 消息交换机的名字*/
public static final String EXCHANGE = "exchangeTest";
/*对列名称*/
public static final String QUEUE_NAME1 = "first-queue";
public static final String QUEUE_NAME2 = "second-queue";

/*
*
* key: queue在该direct-exchange中的key值,当消息发送给direct-exchange中指定key为设置值时,
*   消息将会转发给queue参数指定的消息队列
*/
/** 队列key1*/
public static final String ROUTINGKEY1 = "queue_one_key1";
/** 队列key2*/
public static final String ROUTINGKEY2 = "queue_one_key2";

@Autowired
private QueueConfig queueConfig;
@Autowired
private ExchangeConfig exchangeConfig;

/**
 * 连接工厂
 */
@Autowired
private ConnectionFactory connectionFactory;

/**
 * 将消息队列1和交换机进行绑定,指定队列key1
 */
@Bean
public Binding binding_one() {
    return BindingBuilder.bind(queueConfig.firstQueue()).to(exchangeConfig.directExchange()).with(RabbitMqConfig.ROUTINGKEY1);
}

/**
 * 将消息队列2和交换机进行绑定,指定队列key2
 */
@Bean
public Binding binding_two() {
    return BindingBuilder.bind(queueConfig.secondQueue()).to(exchangeConfig.directExchange()).with(RabbitMqConfig.ROUTINGKEY2);
}

/**
 * queue listener  观察 监听模式
 * 当有消息到达时会通知监听在对应的队列上的监听对象
 * @return
 */
/*@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer_one(){
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer(connectionFactory);
    simpleMessageListenerContainer.addQueues(queueConfig.firstQueue());
    simpleMessageListenerContainer.setExposeListenerChannel(true);
    simpleMessageListenerContainer.setMaxConcurrentConsumers(5);
    simpleMessageListenerContainer.setConcurrentConsumers(1);
    simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
    return simpleMessageListenerContainer;
}*/

/**
 * 自定义rabbit template用于数据的接收和发送
 * 可以设置消息确认机制和回调
 * @return
 */
@Bean
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    // template.setMessageConverter(); 可以自定义消息转换器  默认使用的JDK的,所以消息对象需要实现Serializable

    /**若使用confirm-callback或return-callback,
     * 必须要配置publisherConfirms或publisherReturns为true
     * 每个rabbitTemplate只能有一个confirm-callback和return-callback
     */
    template.setConfirmCallback(msgSendConfirmCallBack());

    /**
     * 使用return-callback时必须设置mandatory为true,或者在配置中设置mandatory-expression的值为true,
     * 可针对每次请求的消息去确定’mandatory’的boolean值,
     * 只能在提供’return -callback’时使用,与mandatory互斥
     */
    template.setReturnCallback(msgSendReturnCallback());
    template.setMandatory(true);
    return template;
}

/*  关于 msgSendConfirmCallBack 和 msgSendReturnCallback 的回调说明:
    1.如果消息没有到exchange,则confirm回调,ack=false
    2.如果消息到达exchange,则confirm回调,ack=true
    3.exchange到queue成功,则不回调return
    4.exchange到queue失败,则回调return(需设置mandatory=true,否则不回回调,消息就丢了)
*/

/**
 * 消息确认机制
 * Confirms给客户端一种轻量级的方式,能够跟踪哪些消息被broker处理,
 * 哪些可能因为broker宕掉或者网络失败的情况而重新发布。
 * 确认并且保证消息被送达,提供了两种方式:发布确认和事务。(两者不可同时使用)
 * 在channel为事务时,不可引入确认模式;同样channel为确认模式下,不可使用事务。
 * @return
 */
@Bean
public MsgSendConfirmCallBack msgSendConfirmCallBack(){
    return new MsgSendConfirmCallBack();
}

@Bean
public MsgSendReturnCallback msgSendReturnCallback(){
    return new MsgSendReturnCallback();
}

}

当生产者发送消息我们需要回调接收到的消息
消息发送到交换机确认机制
public class MsgSendConfirmCallBack implements RabbitTemplate.ConfirmCallback {

@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
    System.out.println("MsgSendConfirmCallBack  , 回调的id:" + correlationData);
    if (ack) {
        System.out.println("消息接收成功");
    } else {
        System.out.println("消息接收失败");
    }
}

}

生产者发送的消息,需要注意的是,如果发送的是对象需要使用到mapper.writeValueAsString进行系列化
(序列化就是将一个对象的状态(各个属性量)保存起来,然后在适当的时候再获得。序列化分为两大部分:序列化和反序列化。序列化是这个过程的第一部分,将数据分解成字节流,以便存储在文件中或在网络上传输。反序列化就是打开字节流并重构对象。对象序列化不仅要将基本数据类型转换成字节表示,有时还要恢复数据。恢复数据要求有恢复数据的对象实例。)
public class FirstSender {

@Autowired
private RabbitTemplate rabbitTemplate;

/**
 * 发送消息
 * @param uuid
 * @param message  消息
 */
public void send(Student uuid, Object message) throws IOException, TimeoutException{
    /*CorrelationData correlationId = new CorrelationData(uuid);*/
    /**
     * RabbitMqConfig.EXCHANGE  指定消息交换机
     * RabbitMqConfig.ROUTINGKEY2  指定队列key2
     */
    ObjectMapper mapper=new ObjectMapper();
    String messaged=mapper.writeValueAsString(uuid);

    rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE, RabbitMqConfig.ROUTINGKEY1,
            messaged.getBytes(), new CorrelationData(1+""));
}

}
消费者接收到的消息
public class FirstConsumer {

/**
 * queues  指定从哪个队列(queue)订阅消息
 * @param message
 */
@RabbitListener(queues = {"first-queue"})
public void handleMessage(Message message)throws IOException, TimeoutException,ShutdownSignalException{
    ObjectMapper mapper=new ObjectMapper();
    String messaged=new String(message.getBody());
    Student student=mapper.readValue(messaged.getBytes("utf-8"),Student.class);
    System.out.println("FirstConsumer {} handleMessage :"+student.getUsername()+student.getPassword());
}

}

发送一个用户对象的数据
public class SendController {

扫描二维码关注公众号,回复: 4778318 查看本文章
@Autowired
private FirstSender firstSender;

@GetMapping("/send")
public String send(String message) throws  Exception,TimeoutException{
    String uuid = UUID.randomUUID().toString();
    Student student=new Student();
    student.setUsername("fsfd");
    student.setPassword("xixix");
    firstSender.send(student,message);
    return uuid;
}

}

猜你喜欢

转载自blog.csdn.net/wuhuayangs/article/details/84861773
今日推荐