1 前置知识
1四种交换机的说明
2主流程的讲解
2 分布式事务
2.1 生产者
2.1.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.1.2yml文件添加配置
server:
port: 8071
spring:
application:
name: biz-publisher
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/publisher?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: 123456
initialSize: 1
minIdle: 3
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#useGlobalDataSourceStat: true
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
#确认消息已发送到交换机(Exchange)
#确认消息已发送到队列(Queue)
publisher-returns: true
# publisher-confirm-type: correlated
publisher-confirms: true
# cloud:
# stream:
# rocketmq:
# binder:
# name-server: 127.0.0.1:9876
# bindings:
# ChannelTrans:
# producer:
# transactional: true
# group: groupTrans
# bindings:
# ChannelTrans:
# destination: topicTrans
mybatis:
configuration:
map-underscore-to-camel-case: true
mapper-locations: mybatis*Mapper.xml
#logging:
# level:
# root: debug
2.1.3 定义交换机
package fastwave.cloud.demo.publisher.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TransConfig {
public static final String TRANSFER_EXCHANGE_NAME = "TransExchange";
public static final String TRANSFER_ROUTING_KEY = "TransRoutingKey";
@Bean
public DirectExchange TransExchange(){
return new DirectExchange(TRANSFER_EXCHANGE_NAME);
}
}
2.1.4 生产者的回调方法(保证消息100%投递)
package fastwave.cloud.demo.publisher.services;
import com.alibaba.fastjson.JSON;
import fastwave.cloud.demo.publisher.config.TransConfig;
import fastwave.cloud.demo.publisher.domain.MsgLogDO;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
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.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.UU