欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot2.5.6集成RabbitMq实现Topic主题模式(推荐)

程序员文章站 2022-06-25 12:19:13
1.application.ymlserver: port: 8184spring: application: name: rabbitmq-demo rabbitmq: host:...

1.application.yml

server:
  port: 8184
spring:
  application:
    name: rabbitmq-demo
  rabbitmq:
    host: 127.0.0.1 # ip地址
    port: 5672
    username: admin # 连接账号
    password: 123456 # 连接密码
    template:
      retry:
        enabled: true # 开启失败重试
        initial-interval: 10000ms # 第一次重试的间隔时长
        max-interval: 300000ms # 最长重试间隔,超过这个间隔将不再重试
        multiplier: 2 # 下次重试间隔的倍数,此处是2即下次重试间隔是上次的2倍
      exchange: topic.exchange # 缺省的交换机名称,此处配置后,发送消息如果不指定交换机就会使用这个
    publisher-confirm-type: correlated # 生产者确认机制,确保消息会正确发送,如果发送失败会有错误回执,从而触发重试
    publisher-returns: true
    listener:
      type: simple
      simple:
        acknowledge-mode: manual
        prefetch: 1 # 限制每次发送一条数据。
        concurrency: 3 # 同一个队列启动几个消费者
        max-concurrency: 3 # 启动消费者最大数量
        # 重试策略相关配置
        retry:
          enabled: true # 是否支持重试
          max-attempts: 5
          stateless: false
          multiplier: 1.0 # 时间策略乘数因子
          initial-interval: 1000ms
          max-interval: 10000ms
        default-requeue-rejected: true

2.pom.xml引入依赖

<!-- rabbitmq -->
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-amqp</artifactid>
        </dependency>

3.常量类创建

/**
 * @author kkp
 * @classname rabbitmqconstants
 * @date 2021/11/3 14:16
 * @description
 */
public class rabbitmqconstants {
    public final static string test1_queue = "test1-queue";

    public final static string test2_queue = "test2-queue";

    public final static string exchange_name = "test.topic.exchange";
    /**
     * routingkey1
     */
    public final static string topic_test1_routingkey = "topic.test1.*";

    public final static string topic_test1_routingkey_test = "topic.test1.test";
    /**
     * routingkey1
     */
    public final static string topic_test2_routingkey = "topic.test2.*";

    public final static string topic_test2_routingkey_test = "topic.test2.test";
}

4.配置configuration

import com.example.demo.common.rabbitmqconstants;
import lombok.extern.slf4j.slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.cachingconnectionfactory;
import org.springframework.amqp.rabbit.core.rabbittemplate;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.beans.factory.config.configurablebeanfactory;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.scope;

/**
 * @author kkp
 * @classname rabbitmqconfig
 * @date 2021/11/3 14:16
 * @description
 */
@slf4j
@configuration
public class rabbitmqconfig {
    @autowired
    private cachingconnectionfactory connectionfactory;

    /**
     *  声明交换机
     */
    @bean(rabbitmqconstants.exchange_name)
    public exchange exchange(){
 //durable(true) 持久化,mq重启之后交换机还在
        // topic模式
        //return exchangebuilder.topicexchange(rabbitmqconstants.exchange_name).durable(true).build();
        //发布订阅模式
        return exchangebuilder.fanoutexchange(rabbitmqconstants.exchange_name).durable(true).build();
    }

    /**
     *  声明队列
     *  new queue(queue_email,true,false,false)
     *  durable="true" 持久化 rabbitmq重启的时候不需要创建新的队列
     *  auto-delete 表示消息队列没有在使用时将被自动删除 默认是false
     *  exclusive  表示该消息队列是否只在当前connection生效,默认是false
     */
    @bean(rabbitmqconstants.test1_queue)
    public queue esqueue() {
        return new queue(rabbitmqconstants.test1_queue);
    }

    /**
     *  声明队列
     */
    @bean(rabbitmqconstants.test2_queue)
    public queue gitalkqueue() {
        return new queue(rabbitmqconstants.test2_queue);
    }

    /**
     *  test1_queue队列绑定交换机,指定routingkey
     */
    @bean
    public binding bindinges(@qualifier(rabbitmqconstants.test1_queue) queue queue,
                             @qualifier(rabbitmqconstants.exchange_name) exchange exchange) {
        return bindingbuilder.bind(queue).to(exchange).with(rabbitmqconstants.topic_test1_routingkey).noargs();
    }

    /**
     *  test2_queue队列绑定交换机,指定routingkey
     */
    @bean
    public binding bindinggitalk(@qualifier(rabbitmqconstants.test2_queue) queue queue,
                                 @qualifier(rabbitmqconstants.exchange_name) exchange exchange) {
        return bindingbuilder.bind(queue).to(exchange).with(rabbitmqconstants.topic_test2_routingkey).noargs();
    }

    /**
     * 如果需要在生产者需要消息发送后的回调,
     * 需要对rabbittemplate设置confirmcallback对象,
     * 由于不同的生产者需要对应不同的confirmcallback,
     * 如果rabbittemplate设置为单例bean,
     * 则所有的rabbittemplate实际的confirmcallback为最后一次申明的confirmcallback。
     * @return
     */
    @bean
    @scope(configurablebeanfactory.scope_prototype)
    public rabbittemplate rabbittemplate() {
         rabbittemplate template = new rabbittemplate(connectionfactory);
        return template;
    }
}

5.rabbit工具类创建

import lombok.extern.slf4j.slf4j;
import org.springframework.amqp.core.message;
import org.springframework.amqp.rabbit.connection.correlationdata;
import org.springframework.amqp.rabbit.core.rabbittemplate;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;

import java.util.uuid;
/**
 * @author kkp
 * @classname rabbitmqutils
 * @date 2021/11/3 14:21
 * @description
 */
@slf4j
@component
public class rabbitmqutils implements rabbittemplate.confirmcallback, rabbittemplate.returncallback{

    private rabbittemplate rabbittemplate;

    /**
     * 构造方法注入
     */
    @autowired
    public rabbitmqutils(rabbittemplate rabbittemplate) {
        this.rabbittemplate = rabbittemplate;
        //这是是设置回调能收到发送到响应
        rabbittemplate.setconfirmcallback(this);
        //如果设置备份队列则不起作用
        rabbittemplate.setmandatory(true);
        rabbittemplate.setreturncallback(this);
    }

    /**
     * 回调确认
     */
    @override
    public void confirm(correlationdata correlationdata, boolean ack, string cause) {
        if(ack){
            log.info("消息发送成功:correlationdata({}),ack({}),cause({})",correlationdata,ack,cause);
        }else{
            log.info("消息发送失败:correlationdata({}),ack({}),cause({})",correlationdata,ack,cause);
        }
    }

    /**
     * 消息发送到转换器的时候没有对列,配置了备份对列该回调则不生效
     * @param message
     * @param replycode
     * @param replytext
     * @param exchange
     * @param routingkey
     */
    @override
    public void returnedmessage(message message, int replycode, string replytext, string exchange, string routingkey) {
        log.info("消息丢失:exchange({}),route({}),replycode({}),replytext({}),message:{}",exchange,routingkey,replycode,replytext,message);
    }

    /**
     * 发送到指定queue
     * @param queuename
     * @param obj
     */
    public void send(string queuename, object obj){
        correlationdata correlationid = new correlationdata(uuid.randomuuid().tostring());
        this.rabbittemplate.convertandsend(queuename, obj, correlationid);
    }

    /**
     * 1、交换机名称
     * 2、routingkey
     * 3、消息内容
     */
    public void sendbyroutingkey(string exchange, string routingkey, object obj){
        correlationdata correlationid = new correlationdata(uuid.randomuuid().tostring());
        this.rabbittemplate.convertandsend(exchange, routingkey, obj, correlationid);
    }
}

6.service创建

public interface testservice {

    string sendtest1(string content);

    string sendtest2(string content);
}

7.impl实现

import com.example.demo.common.rabbitmqconstants;
import com.example.demo.util.rabbitmqutils;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
/**
 * @author kkp
 * @classname testserviceimpl
 * @date 2021/11/3 14:24
 * @description
 */
@service
@slf4j
public class testserviceimpl implements testservice {

    @autowired
    private rabbitmqutils rabbitmqutils;

    @override
    public string sendtest1(string content) {
        rabbitmqutils.sendbyroutingkey(rabbitmqconstants.exchange_name,
                rabbitmqconstants.topic_test1_routingkey_test, content);
        log.info(rabbitmqconstants.topic_test1_routingkey_test+"***************发送成功*****************");
        return "发送成功!";
    }

    @override
    public string sendtest2(string content) {
        rabbitmqutils.sendbyroutingkey(rabbitmqconstants.exchange_name,
                rabbitmqconstants.topic_test2_routingkey_test, content);
        log.info(rabbitmqconstants.topic_test2_routingkey_test+"***************发送成功*****************");
        return "发送成功!";
    }
}

8.监听类

import com.example.demo.common.rabbitmqconstants;
import lombok.extern.slf4j.slf4j;
import org.springframework.amqp.core.exchangetypes;
import org.springframework.amqp.core.message;
import org.springframework.amqp.rabbit.annotation.exchange;
import org.springframework.amqp.rabbit.annotation.queue;
import org.springframework.amqp.rabbit.annotation.queuebinding;
import org.springframework.amqp.rabbit.annotation.rabbitlistener;
import org.springframework.stereotype.component;

import com.rabbitmq.client.channel;

/**
 * @author kkp
 * @classname rabbitmqlistener
 * @date 2021/11/3 14:22
 * @description
 */

@slf4j
@component
public class rabbitmqlistener {

    @rabbitlistener(queues = rabbitmqconstants.test1_queue)
    public void test1consumer(message message, channel channel) {
        try {
            //手动确认消息已经被消费
            channel.basicack(message.getmessageproperties().getdeliverytag(), false);
            log.info("counsoum1消费消息:" + message.tostring() + "。成功!");
        } catch (exception e) {
            e.printstacktrace();
            log.info("counsoum1消费消息:" + message.tostring() + "。失败!");
        }
    }

    @rabbitlistener(queues = rabbitmqconstants.test2_queue)
    public void test2consumer(message message, channel channel) {
        try {
            //手动确认消息已经被消费
            channel.basicack(message.getmessageproperties().getdeliverytag(), false);
            log.info("counsoum2消费消息:" + message.tostring() + "。成功!");
        } catch (exception e) {
            e.printstacktrace();
            log.info("counsoum2消费消息:" + message.tostring() + "。失败!");
        }
    }

}

9.controller测试

import com.example.demo.server.testservice;
import jdk.nashorn.internal.objects.annotations.getter;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;

import java.util.map;

/**
 * @author kkp
 * @classname testcontroller
 * @date 2021/11/3 14:25
 * @description
 */
@slf4j
@restcontroller
@requestmapping("/enterprise")
public class testcontroller {

    @autowired
    private testservice testservice;

    @getmapping("/finance")
    public string hello3(@requestparam(required = false) map<string, object> params) {
        return testservice.sendtest2(params.get("entid").tostring());
    }
    /**
     * 发送消息test2
     * @param content
     * @return
     */
    @postmapping(value = "/finance2")
    public string sendtest2(@requestbody string content) {
        return testservice.sendtest2(content);
    }

}

springboot2.5.6集成RabbitMq实现Topic主题模式(推荐)

到此这篇关于springboot2.5.6集成rabbitmq实现topic主题模式的文章就介绍到这了,更多相关springboot集成rabbitmq内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!