spring-boot整合rabbitMQ

本文介绍了如何在Spring Boot项目中整合并使用RabbitMQ,包括MQ的配置、测试Controller的实现、Mail实体的定义、消息接收类的设计以及application.yml配置文件的详细说明。参考了相关CSDN博客文章进行实战操作。
摘要由CSDN通过智能技术生成

MQ配置项


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitmqConfig {


    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Autowired
    private SimpleRabbitListenerContainerFactoryConfigurer factoryConfigurer;

    private static final Logger log = LoggerFactory.getLogger(RabbitmqConfig.class);

    @Bean
    public RabbitTemplate rabbitTemplate() {
        connectionFactory.setPublisherConfirms(true);
        connectionFactory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause));
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message));
        return rabbitTemplate;
    }

    @Bean(name = "justiceQueue")
    public Queue justiceQueue() {
        return new Queue("justiceQueue", true);
    }

    @Bean
    public DirectExchange justiceExchange() {
        return new DirectExchange("justiceExchange", true, false);
    }

    @Bean
    public Binding justiceBinding(Queue queue, DirectExchange directExchange) {
        return BindingBuilder.bind(queue).to(directExchange).with("justiceRoutingKey");
    }
}

MQ测试controller


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ojama.entity.Mail;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class TestController {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ObjectMapper objectMapper;

    @RequestMapping("/hello")
    public Mail userRegister(String name, String password) throws JsonProcessingException {
        Mail mail = new Mail()
                .setContent("hello!,your name is " + name + ",your password is " + password)
                .setFrom("785607860@qq.com")
                .setTo("1061037698@qq.com")
                .setSubject("hello");
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange("justiceExchange");
        rabbitTemplate.setRoutingKey("justiceRoutingKey");
        Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(mail)).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
        message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MessageProperties.CONTENT_TYPE_JSON);
        rabbitTemplate.convertAndSend(message);
        return mail;
    }
}

Mail实体


import java.io.Serializable;

public class Mail implements Serializable {
    private String from;
    private String to;
    private String subject;
    private String content;

    public String getFrom() {
        return from;
    }

    public Mail setFrom(String from) {
        this.from = from;
        return this;
    }

    public String getTo() {
        return to;
    }

    public Mail setTo(String to) {
        this.to = to;
        return this;
    }

    public String getSubject() {
        return subject;
    }

    public Mail setSubject(String subject) {
        this.subject = subject;
        return this;
    }

    public String getContent() {
        return content;
    }

    public Mail setContent(String content) {
        this.content = content;
        return this;
    }
}

消息接收类:


import com.fasterxml.jackson.databind.ObjectMapper;
import ojama.entity.Mail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@RabbitListener(queues = "justiceQueue")
public class MqHandler {

    @Resource
    private ObjectMapper objectMapper;

    private static final Logger log = LoggerFactory.getLogger(MqHandler.class);

    @RabbitHandler
    public void forTheKing(@Payload byte[] message) {
        try {
            Mail mail = objectMapper.readValue(message, Mail.class);
            System.out.println(mail);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

application.yml配置

spring:
  rabbitmq:
    host: localhost
    username: mqadmin
    password: mqadminpassword

参考文章:https://blog.csdn.net/u013871100/article/details/82982235

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值