02.SpringBoot整合RabbitMQ和P2P例子

02.SpringBoot整合RabbitMQ和P2P例子,第1张

02.SpringBoot整合RabbitMQ和P2P例子 SpringBoot整合RabbitMQ和P2P例子

SpringBoot 整合rabbitmq很简单,使用amqp即可。

p2p即点对点,一条消息被一个队列消费,是消息队列最基本中的模式

例如如下场景:聊天程序中的单聊

pom文件



    4.0.0

    org.example
    rabbitmq-client
    1.0-SNAPSHOT
    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.2
    
    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-amqp
        
    


application.yml

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
    virtual-host: /

启动类无需加任何配置

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
生产者

使用接口来模拟生产者

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserCtrl {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @GetMapping("/addUser")
    public String addUser(String name){
        String queueName = "USER";
        amqpTemplate.convertAndSend(queueName, name);
        return name;
    }
}

打开rabbitmq管理页面:http://localhost:15672/#/queues

添加一个USER队列

访问接口地址:http://localhost:8080/addUser?name=terry

可以看到队列中已经产生了1条数据

消费者
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "USER")
public class P2PUserConsumer {

    @RabbitHandler
    public void receive(String msg){
        System.out.println("消费者消费的消息:" + msg);
    }
}

重启项目,此时消费者会吧之前生成的消息消费掉

此时我们再生产一条新消息

看到打印后,P2P完成!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5702171.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存