SpringBoot与RabbitMQ

配置

引入依赖amqp的starter(spring-boot-starter-amqp)
application.properties中rabbitMQ配置

spring.rabbitmq.host=192.168.137.3
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

SpringBoot主程序

**
 * 自动配置
 *  1、RabbitAutoConfiguration
 *  2、有自动配置了连接工厂ConnectionFactory;
 *  3、RabbitProperties 封装了 RabbitMQ的配置
 *  4、 RabbitTemplate :给RabbitMQ发送和接受消息;
 *  5、 AmqpAdmin : RabbitMQ系统管理功能组件;
 *      AmqpAdmin:创建和删除 Queue,Exchange,Binding
 *  6、@EnableRabbit +  @RabbitListener 监听消息队列的内容
 *
 */
@EnableRabbit  //开启基于注解的RabbitMQ模式,若系统中没有Rabbit注解则不需要
@SpringBootApplication
public class AmqpApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02AmqpApplication.class, args);
    }
}

RabbitMQConfig

@Configuration
public class RabbitMQConfig {
    //采用json数据格式发送消息
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}

测试类

    @Autowired
    RabbitTemplate rabbitTemplate;  //消息处理发送组件
    //1、Message需要自己构造一个;定义消息体内容和消息头rabbitTemplate.send(exchage,routeKey,message);
    //2、rabbitTemplate.convertAndSend(exchage,routeKey,object);
    @Test
    void Test1(){
        Student stu = studentMapper.getStudentById(1);
        rabbitTemplate.convertAndSend("exchanges.topic","anxglee",stu);
        //rabbitTemplate.convertAndSend("exchanges.direct","anxglee","hello,somebody");
    }
    @Autowired
    AmqpAdmin amqpAdmin; //管理组件
    @Test
    void Test2(){
        Exchange exchange = new DirectExchange("admin.direct");
        amqpAdmin.declareExchange(exchange);
        Queue queue = new Queue("admin.queue",true);
        amqpAdmin.declareQueue(queue);
        Binding binding = new Binding("admin.queue",Binding.DestinationType.QUEUE,"admin.direct","admin.queue",null);
        amqpAdmin.declareBinding(binding);
    }
    //接受数据,如何将数据自动的转为json发送出去
    @Test
     public void Test3(){
          Object obj = rabbitTemplate.receiveAndConvert("admin.news");
          System.out.println(obj.getClass());
          System.out.println(obj);
    }

@RabbitListener

@Service
public class StudentService {

    @RabbitListener(queues = "admin.news") 
    public void receive(Student student){
        //测试类中给admin.news发送的消息体为Student类型,所以将收到的消息直接反序列到student中了
        System.out.println("收到消息:"+ student);
    }

    @RabbitListener(queues = "admin")
    public void receive02(Message message){
        //org.springframework.amqp.core.Message类型,可以获取消息体和消息头等内容
        System.out.println(message.getBody());
        System.out.println(message.getMessageProperties());
    }
}

你可能感兴趣的:(SpringBoot与RabbitMQ)