Java学习之路

RabbitMQ

2019-07-14  本文已影响63人  椰子奶糖

RabbitMQ

简介:

核心概念

Message:

Publisher

Exchange

Queue

Binding

Connection

Channel

Customer

Virtual Host

Broker

消息机制原理

docker一个RabbitMQ...

sptingboot中RabbitMQ的配置原理

        spring.rabbitmq.username=guest
        spring.rabbitmq.password=guest
        spring.rabbitmq.port=5672
        #spring.rabbitmq.virtual-host=/
        username,assword,port,virtual-host:都可以不写,前两者默认为guest,port默认为5672,virtual-host:默认为/

测试:发送消息与接收消息(接收消息可以使用监听器完成)

@AutowiredRabbit
Template rabbitTemplate;

@Test
public void contextLoads() {      
        Map<String, Object> map = new HashMap<>();      
        map.put("msg","这是第一个消息");      
        map.put("data", Arrays.asList("helloworld", 123, true));       
        //对象被序列化后发送出去       
        rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",map);
}
//接受数据,将数据自动转为JSON发出去(Jackson2JsonMessageConverter)
@Testpublic 
void receive(){       
        Object o = rabbitTemplate.receiveAndConvert("atguigu.news");       
        System.out.println(o.getClass());      
        System.out.println(o);
}

配置:使用Jackson2JsonMessage

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** 
* Created by CHEN on 2019/7/14. 
*/
@Configurationpublic 
class MyAMQPConfig {    
        @Bean    
        public MessageConverter message(){       
            //配置使用Jackson2JsonMessageConverter序列化器
            return  new Jackson2JsonMessageConverter();   
        }
}

接收消息的两种模式:

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
/** 
* Created by CHEN on 2019/7/14. 
*/
@Servicepublic class BookService {    

        @RabbitListener(queues = "atguigu.emps")    
        public void receive(Object object) {        
                System.out.println(object);    
        }    
        
        @RabbitListener(queues = "atguigu.news")    
        public void receiveMessage(Message message) {     
                System.out.println(message.getBody());       
                System.out.println(message.getMessageProperties());   
        }
}

AmqpAdmin来创建、修改绑定Exchange和QueneDemo:

       amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
       System.out.println("创建完成");
       amqpAdmin.declareQueue(new 
       Queue("amqpadmin.queue",true));          
        //创建绑定规则
       amqpAdmin.declareBinding(new inding("amqpadmin.queue", inding.DestinationType.QUEUE, amqpadmin.exchange","amqp.haha",null));     
上一篇 下一篇

猜你喜欢

热点阅读