栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

02.SpringBoot整合RabbitMQ和P2P例子

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完成!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/702063.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号