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

进行测试:

相关推荐
白宇横流学长11 分钟前
基于SpringBoot实现的大创管理系统设计与实现【源码+文档】
java·spring boot·后端
fat house cat_38 分钟前
【redis】线程IO模型
java·redis
stein_java2 小时前
springMVC-10验证及国际化
java·spring
weixin_478689762 小时前
C++ 对 C 的兼容性
java·c语言·c++
LUCIAZZZ2 小时前
HikariCP数据库连接池原理解析
java·jvm·数据库·spring·springboot·线程池·连接池
sky_ph2 小时前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
IDRSolutions_CN3 小时前
PDF 转 HTML5 —— HTML5 填充图形不支持 Even-Odd 奇偶规则?(第二部分)
java·经验分享·pdf·软件工程·团队开发
hello早上好3 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
HelloWord~4 小时前
SpringSecurity+vue通用权限系统2
java·vue.js
让我上个超影吧4 小时前
黑马点评【基于redis实现共享session登录】
java·redis