zoukankan      html  css  js  c++  java
  • SpringBoot整合RabbitMQ

    1.导入相应依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>

    2.在测试类里进行测试

    package com.ws;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    @SpringBootTest
    class Springboot02AmqpApplicationTests {
        @Autowired
        RabbitTemplate rabbitTemplate;
        @Test
        void contextLoads() {
            /*message需要自己构造一个;定义消息体内容和消息头
            *rabbitTemplate.send(exchange,routeKey,message)
            *
            * object默认当成消息体,只需要传入发送的对象,自动序列化发给rabbitmq
            * rabbitTemplate.convertAnd Send(exchange,routeKey,object)
            * */
            Map<String, Object> map = new HashMap<>();
            map.put("msg","one");
            map.put("data", Arrays.asList("HelloWorld",111));
            rabbitTemplate.convertAndSend("exchange.direct","ws.news",map);
        }
        @Test
        void test2(){
            Object o = rabbitTemplate.receiveAndConvert("ws.news");
            System.out.println(o.getClass());
            System.out.println(o);
    
        }
    }

    3.编写自己的序列化Bean

    import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.amqp.support.converter.MessageConverter;
    
    @Configuration
    public class MyAMQPConfig {
        @Bean
        public MessageConverter messageConverter(){
          return new Jackson2JsonMessageConverter();
        }
    }

     4.使用监听时需要在主启动类上加上@EnableRabbit注解

       在方法上加@RabbitListener(queues="")注解,当消息队列里有值的时候就会被取出

     @RabbitListener(queues = "ws.news")
        public void get(User user){
            System.out.println("get"+user);
        }
        @RabbitListener(queues = "ws.news")
        public void get2(Message message){
            System.out.println(message.getBody());
            System.out.println(message.getMessageProperties());
        }
  • 相关阅读:
    select在各个浏览器中的兼容性问题
    pc打开手机站提示切换为手机屏幕
    图片预加载
    div盒子水平垂直居中的方法
    如何检测该浏览器为微信浏览器
    小箭头的写法,z-index在ie7显示混乱问题
    微信a标签不跳转
    css font简写规则
    windows环境cmd下执行jar
    docker制作镜像步骤
  • 原文地址:https://www.cnblogs.com/ws-sharecode/p/13426551.html
Copyright © 2011-2022 走看看