7.RabbitMQ 消费者Consumer实现

1、创建Consumer的接口RabbitMqService:

package com.java996.consumer.service;

public interface RabbitMqService {

    /**
     * 接收消息
     */
    public void receiveMessage();
}

2、创建Consumer的接口的实现RabbitMqServiceImpl:

package com.java996.consumer.service.impl;

import com.java996.consumer.service.RabbitMqService;
import com.java996.producer.config.RabbitMqConfig;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("RabbitMqService")
public class RabbitMqServiceImpl implements RabbitMqService {

    @Resource
    private AmqpTemplate amqpTemplate;

    /**
     * receiveAndConvert(String queueName),参数说明:队列名称
     */
    @Override
    public void receiveMessage() {
        String message = (String)amqpTemplate.receiveAndConvert(RabbitMqConfig.DIRECT_QUEUE);
        System.out.println("接收到的消息:"+message);
    }
}

3、启动,测试接收消息

package com.java996.consumer;

import com.java996.consumer.service.RabbitMqService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class ConsumerApp {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(ConsumerApp.class,args);
        RabbitMqService rabbitMqService = (RabbitMqService) context.getBean("RabbitMqService");
        rabbitMqService.receiveMessage();
    }
}

4、结果:
在这里插入图片描述
这种方式只能拿到一条数据,所以需要换一种方式

5、监听队列,首先保证队列中有多条消息,启动项中的消费代码已注释或删除

@Override
@RabbitListener(queues = {RabbitMqConfig.DIRECT_QUEUE}) //监听队列
public void receiveMessage2(String message) {
    System.out.println("接收到的消息:"+message);
}

6、结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值