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

创建了两个项目 ,一个是 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 项目中的打印信息

在这里插入图片描述

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐