RabbitMQ 简单入门 (微服务)

简单实现"消息的生成"以及"消息的消费"

创建了两个项目 ,一个是 Producer项目 ,一个Customer 项目
在这里插入图片描述
分别在两个项目添加的Rabbit依赖:

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

先创建 Producer项目

配置文件 application.yml:

server:
  port: 8888

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

ProducerController :生成消息

@RestController
@RequestMapping
public class ProducerController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public String sendPhoneCode(@RequestParam String phone, @RequestParam String code) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        //将手机号与验证码发送给rabbitmq队列
        rabbitTemplate.convertAndSend("wuxin", map);
        return "成功发送验证码";
    }
}

创建 Customer 项目

配置文件 application.yml:

server:
  port: 9999

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

方案一:Rabbit初始化配置文件,消息队列 "wuxin"

@Lazy
@Configuration
public class RabbitInitConfig {

    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;

    @Bean
    public Queue helloQueue() {
        return new Queue("wuxin");
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true);
        return connectionFactory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }
}

方案二:如果不用rabbit配置类,则需要到网页上配置好队列名称,否则启动项目时会报“找不到queue=“wuxin” 的错误信息 ”
在这里插入图片描述

消费消息(注意:队列名称一定要一致!!!)
@RabbitListener(queues = “wuxin”) 也可以直接写在方法上

@Component
@RabbitListener(queues = "wuxin")
public class Customer {

    @RabbitHandler
    public void receive(Map<String, String> map){
        String phone= map.get("phone");
        String code= map.get("code");
        System.out.println(phone+"__"+code);
    }

}

确保两个项目启动成功后,调用 Producer 项目中的 "send"接口
在这里插入图片描述
查看 Customer 项目中的打印信息

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值