RabbitMQ消息队列

首先引入相关依赖:

java 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

配置applicaiton.yml:

XML 复制代码
server:
  port: 8082
spring:
  rabbitmq:
    host: 192.168.37.105
    port: 5672
    username: admin
    password: admin
    virtual-host: /

shop:
  exchange: shop.exchange.direct
  queue: shop.queue
  routingKey: shop.routingKey

编写配置类RabbitMqConfig:

java 复制代码
@Configuration
public class RabbitmqConfig {

    @Value("${shop.exchange}")
    private String exchange;
    @Value("${shop.queue}")
    private String queue;
    @Value("${shop.routingKey}")
    private String routingKey;

    @Bean
    public Exchange getExchange(){
        return new DirectExchange(exchange);
    }

    @Bean
    public Queue getQueue(){
        return new Queue(queue);
    }

    @Bean
    public Binding binding(Exchange exchange,Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with(routingKey).noargs();
    }

    /**
     * 消息转化器
     * 将对象转化为 Json 字符串
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}

如果不配置消息转化器,默认只能处理字符串消息。不能处理对象!!!

创建生产者:

java 复制代码
@RestController
@RequiredArgsConstructor
@RequestMapping("producer02")
public class Producer02Controller {

    @Value("${shop.exchange}")
    private String exchange;

    @Value("${shop.routingKey}")
    private String routingKey;

    private final RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public String sendMsg(){
        rabbitTemplate.convertAndSend(exchange,routingKey,new Student(2,"Alice","178",20));
        return "Producer02==>发送成功!";
    }
}

创建消费者(获取消息):

java 复制代码
@Component
public class MegListener {

    @RabbitListener(queues = "${shop.queue}")
    public void readStu(String msg) {
        System.out.println("shop.queue:" + msg);
    }

    @RabbitListener(queues = "${shop.queue}")
    public void readStu(Student stu) {
        System.out.println("shop.queue:" + stu);
    }
}

创建实体类:

java 复制代码
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Student implements Serializable {
    private Integer id;
    private String name;
    private String phone;
    private Integer age;
}

进行测试:

相关推荐
rabbit_pro2 分钟前
Java使用Mybatis-Plus封装动态数据源工具类
java·python·mybatis
期待のcode8 分钟前
Java虚拟机类加载机制
java·开发语言
短剑重铸之日15 分钟前
《SpringBoot4.0初识》第四篇:原生镜像
java·原生镜像·springboot4.0
程序员欣宸18 分钟前
LangChain4j实战之十二:结构化输出之三,json模式
java·人工智能·ai·json·langchain4j
天若有情67336 分钟前
打破思维定式!C++参数设计新范式:让结构体替代传统参数列表
java·开发语言·c++
亲爱的非洲野猪41 分钟前
从ReentrantLock到AQS:深入解析Java并发锁的实现哲学
java·开发语言
wheelmouse778843 分钟前
如何设置VSCode打开文件Tab页签换行
java·python
yangminlei1 小时前
Spring Boot——日志介绍和配置
java·spring boot
廋到被风吹走1 小时前
【Spring】Spring Boot Starter设计:公司级监控SDK实战指南
java·spring boot·spring
码头整点薯条1 小时前
启动报错:Invalid value type for attribute ‘factoryBeanObjectType‘ 解决方案
java