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;
}

进行测试:

相关推荐
程序员西西6 分钟前
SpringBoot接口安全:APIKey保护指南
java·spring boot·计算机·程序员·编程·编程开发
summer_west_fish24 分钟前
单体VS微服务:架构选择实战指南
java·微服务·架构
v***85727 分钟前
Ubuntu介绍、与centos的区别、基于VMware安装Ubuntu Server 22.04、配置远程连接、安装jdk+Tomcat
java·ubuntu·centos
烤麻辣烫34 分钟前
黑马程序员大事件后端概览(表现效果升级版)
java·开发语言·学习·spring·intellij-idea
q***965837 分钟前
Spring总结(上)
java·spring·rpc
思密吗喽38 分钟前
宠物商城系统
java·开发语言·vue·毕业设计·springboot·课程设计·宠物
ss2731 小时前
019:深入解析可重入互斥锁:原理、实现与线程安全实践
java·数据库·redis
luyun0202021 小时前
牛批了,某音录播神器
java·windows·figma
高级程序源1 小时前
springboot社区医疗中心预约挂号平台app-计算机毕业设计源码16750
java·vue.js·spring boot·mysql·spring·maven·mybatis
y***61312 小时前
SpringBoot集成Flowable
java·spring boot·后端