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