RabbitMQ 整合springboot注解开发

 

首先搭建一个springboot环境,这里可以使用ideaRabbitMQ 整合springboot注解开发_第1张图片为我们构建,也可以去 http://spring.io 

next填好项目得groupid之类得到这里我们单单选择一个web即可.

RabbitMQ 整合springboot注解开发_第2张图片

 

加入springboot关于amqp得启动器:

spring-boot-starter-amqp

RabbitMQ 整合springboot注解开发_第3张图片

 

  1. 编写一个consumenr:
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "${spring.rabbitmq.queue}", autoDelete = "true"),
        exchange = @Exchange(value = "${spring.rabbitmq.exchange}", type = ExchangeTypes.DIRECT),
        key = "${spring.rabbitmq.routing_key}"
))
public class MqReciver {

    @RabbitHandler
    public void PrintLog(String msg) {
        System.out.println("我是消息接收者:打印" + msg);
    }

在配置文件application.yml中配置rabbitmq

spring:
  rabbitmq:
    addresses: #######     //mq服务地址
    port: 5672
    username: wuqw
    password: ####
    routing_key: test_msg      //定义路由键名称
    exchange: test_exchange    //定义交换器名
    queue: test_queue          //定义队列
    #开启重试,如果不开启一旦消费者故障,发送者会一直向队列中发送这个消息
    listener:
      retry:
        enabled: true
        #重试次数
        max-attempts: 2

 

2.编写一个provider发送者:

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;

import java.util.UUID;
/*纯java代码实现发送*/

public class Mqsender implements RabbitTemplate.ConfirmCallback {
    int flag1 = 0;

    public void send() {
        int flag = flag1++;
        CorrelationData correlationData = new 
        CorrelationData(UUID.randomUUID().toString());
        ConnectionFactory bean = getBean();
        AmqpTemplate amqpTemplate = new RabbitTemplate(bean);
        ((RabbitTemplate) amqpTemplate).convertAndSend("test_exchange", "test_msg", "成功测试" + flag, correlationData);   
        //确认
        ((RabbitTemplate) amqpTemplate).setConfirmCallback(this);
    }

    public ConnectionFactory getBean() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setHost("***88");
        cachingConnectionFactory.setPort(5672);
        cachingConnectionFactory.setUsername("wuqw");
        cachingConnectionFactory.setPassword("*******");
        return cachingConnectionFactory;
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b) {
        System.out.println("回调确认消息状态" + correlationData);
        if (b) {
            System.out.println("消息发送成功");
        } else {
            System.out.println("消息发送失败");
        }
    }

 

你可能感兴趣的:(RabbitMQ)