在这里插入代码片
public class RabbitConst {
public final static String PAY_EXCHANGE_TOPIC = "xa.pay";
public final static String PAY_SUCCESS_QUEUES = "xa.pay.success";
public final static String PAY_SUCCESS_QUEUES2 = "xa.pay.success2";
public final static String EXCHANGE_TOPIC = "delay.topic";
public final static String DELAY_QUEUES = "delay.exchange.topice";
public final static String PRIORITY_TOPIC = "priority.exchange";
public final static String PRIORITY_QUEUES = "priority.exchange.topice";
public final static String PRIORITY_TOPIC_1 = "priority.exchange1";
public final static String PRIORITY_QUEUES_1 = "priority.exchange1.topice1";
public static final String DELAY_EXCHSNGE_NAME = "delay.exchange";
public static final String TIMEOUT_TRADE_QUEUE_NAME = "closeTrade";
public static final String TIMEOUT_TRADE_QUEUE_NAME2 = "closeTrade2";
public static final String DEFAULT_EXCHSNGE_NAME = "order.exchange";
public static final String ORDER_PAY_QUEUE_NAME = "orderPay";
}
import java.util.HashMap;
import java.util.Map;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
@Bean
TopicExchange PaySuccessExchange() {
return new TopicExchange(RabbitConst.PAY_EXCHANGE_TOPIC);
}
@Bean
Binding bindingEmailExchangeMessagePay() {
return BindingBuilder
.bind(paySuccessMessage())
.to(PaySuccessExchange())
.with("xa.pay.*");
}
@Bean
public Queue paySuccessMessage() {
return new Queue(RabbitConst.PAY_SUCCESS_QUEUES);
}
@Bean
Binding bindingEmailExchangeMessagePay2() {
return BindingBuilder
.bind(paySuccessMessage2())
.to(PaySuccessExchange())
.with("xa.pay.*");
}
@Bean
public Queue paySuccessMessage2() {
return new Queue(RabbitConst.PAY_SUCCESS_QUEUES2);
}
@Bean
TopicExchange delayExchangTopice() {
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-delayed-type", "topic");
TopicExchange topicExchange = new TopicExchange(RabbitConst.EXCHANGE_TOPIC, true, false, args);
topicExchange.setDelayed(true);
return topicExchange;
}
@Bean
Binding bindingEmailExchangeMessageTopic() {
return BindingBuilder
.bind(mssageTopic())
.to(delayExchangTopice())
.with("delay.exchange.*");
}
@Bean
public Queue mssageTopic() {
return new Queue(RabbitConst.DELAY_QUEUES);
}
@Bean
TopicExchange priorityExchangTopice() {
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-max-priority", 5);
TopicExchange topicExchange = new TopicExchange(RabbitConst.PRIORITY_TOPIC, true, false, args);
return topicExchange;
}
@Bean
Binding bindingpriorityExchangTopice() {
return BindingBuilder
.bind(priorityExchangTopiceMessage())
.to(priorityExchangTopice())
.with("priority.exchange.*");
}
@Bean
public Queue priorityExchangTopiceMessage() {
return new Queue(RabbitConst.PRIORITY_QUEUES);
}
@Bean
TopicExchange priorityExchangTopice1() {
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-max-priority", 7);
TopicExchange topicExchange = new TopicExchange(RabbitConst.PRIORITY_TOPIC_1, true, false, args);
return topicExchange;
}
@Bean
Binding bindingpriorityExchangTopice1() {
return BindingBuilder
.bind(priorityExchangTopiceMessage1())
.to(priorityExchangTopice1())
.with("priority.exchange1.*");
}
@Bean
public Queue priorityExchangTopiceMessage1() {
return new Queue(RabbitConst.PRIORITY_QUEUES_1);
}
@Bean
public Queue delayPayQueue() {
return new Queue(RabbitConst.TIMEOUT_TRADE_QUEUE_NAME);
}
@Bean
public Binding delayPayBind() {
return BindingBuilder.bind(delayPayQueue()).to(delayExchange());
}
@Bean
public Queue delayPayQueue2() {
return new Queue(RabbitConst.TIMEOUT_TRADE_QUEUE_NAME2);
}
@Bean
public Binding delayPayBind2() {
return BindingBuilder.bind(delayPayQueue2()).to(delayExchange());
}
@Bean
FanoutExchange delayExchange(){
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-delayed-type", "fanout");
FanoutExchange topicExchange = new FanoutExchange(RabbitConst.DELAY_EXCHSNGE_NAME, true, false, args);
topicExchange.setDelayed(true);
return topicExchange;
}
@Bean
public Queue orderPayQueue(){
return new Queue(RabbitConst.ORDER_PAY_QUEUE_NAME);
}
@Bean
public DirectExchange defaultExchange() {
return new DirectExchange(RabbitConst.DEFAULT_EXCHSNGE_NAME, true, false);
}
@Bean
public Binding orderPayBind(){
return BindingBuilder.bind(orderPayQueue()).to(defaultExchange()).with(RabbitConst.ORDER_PAY_QUEUE_NAME);
}
@Bean
Jackson2JsonMessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(jsonMessageConverter());
return rabbitTemplate;
}
@Bean
RabbitAdmin rabbitAdmin(final ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
}
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import org.springframework.amqp.core.Message;
import lombok.extern.log4j.Log4j2;
@Log4j2
@Component
public class RabbitMessageConfirm implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback{
@Autowired
private RabbitTemplate rabbitTemplate;
@PostConstruct
public void init(){
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnCallback(this);
}
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
log.info(correlationData.getId()+"---RabbitCouponSend confirm---: "+ack);
String id = correlationData.getId();
if(ack){
log.info("----------------confirm---------------------------"+id );
}else{
log.info("----------------confirm---------------------------"+id);
}
}
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
log.error("---消息主体 message : "+message);
log.error("---消息主体 message : "+replyCode);
log.error("---描述:"+replyText);
log.error("---消息使用的交换器 exchange : "+exchange);
log.error("---消息使用的路由键 routing : "+routingKey);
}
}
import java.io.IOException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
@Log4j2
@Component
public class RabbitmqConsumerDelayFanout {
@RabbitListener(queues = RabbitConst.TIMEOUT_TRADE_QUEUE_NAME)
public void delayedProcess(String content, Message message, Channel channel) throws IOException {
try {
log.info("***************process************延迟队列的内容", content);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("超时信息处理完毕");
} catch (Exception e) {
log.error("处理失败*********************", e.getMessage());
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
@RabbitListener(queues = RabbitConst.TIMEOUT_TRADE_QUEUE_NAME2)
public void delayedProcess2(String content, Message message, Channel channel) throws IOException {
try {
log.info("!!!!!!!!!!!!!!!process2!!!!!!!!!!!!!!!!!!!!!!!!1延迟队列的内容[{}]", content);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!超时信息处理完毕");
} catch (Exception e) {
log.error("处理失败*********************", e.getMessage());
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
}
import java.io.IOException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
@Log4j2
@Component
public class RabbitmqConsumerDelayTopic {
@RabbitListener(queues = RabbitConst.DELAY_QUEUES)
public void topicProcess(String content, Message message, Channel channel) throws IOException {
try {
log.info("*******topic********process************延迟队列的内容", content);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("*******topic******超时信息处理完毕");
} catch (Exception e) {
log.error("处理失败*********************", e.getMessage());
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
@RabbitListener(queues = RabbitConst.PAY_SUCCESS_QUEUES)
public void messageProcess(String msg, Channel channel, Message message) throws IOException{
try {
log.info("---mq--%%%%%%%%%%%%-----pay--notify--result--" + msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (IOException e) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
log.error("---mq--%%%%%%%%%%%%-----pay--notify--result--="+msg);
log.error("---mq--%%%%%%%%%%%%-----pay--notify--result--error--"+e);
}
}
@RabbitListener(queues = RabbitConst.PAY_SUCCESS_QUEUES2)
public void messageProcess2(String msg, Channel channel, Message message) throws IOException{
try {
log.info("--2-mq--%%%%%%%%%%%%-----pay--notify--result--" + msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (IOException e) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
log.error("--2-mq--%%%%%%%%%%%%-----pay--notify--result--="+msg);
log.error("--2-mq--%%%%%%%%%%%%-----pay--notify--result--error--"+e);
}
}
@RabbitListener(queues = RabbitConst.PRIORITY_QUEUES)
public void priority1(String msg, Channel channel, Message message) throws IOException{
log.info("-----*******************************-----priority1--notify--result--" + msg);
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
@RabbitListener(queues = RabbitConst.PRIORITY_QUEUES_1)
public void priority2(String msg, Channel channel, Message message) throws IOException{
log.info("--------------------------------------------------priority2--notify--result--" + msg);
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
}
import java.io.IOException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
@Log4j2
@Component
public class RabbitmqConsumerDirect {
@RabbitListener(queues = RabbitConst.ORDER_PAY_QUEUE_NAME)
public void directProcess(String content, Message message, Channel channel) throws IOException {
try {
log.info("普通队列的内容*********************", content);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
log.error("处理失败*********************", e.getMessage());
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
}
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitmqPublishDelayFanout {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendTimeoutMsg(String msge, int delay, String id){
CorrelationData correlationData = new CorrelationData(id);
rabbitTemplate.convertAndSend(RabbitConst.DELAY_EXCHSNGE_NAME, "", msge, message ->{
message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
message.getMessageProperties().setDelay(delay * 1000);
return message;
},correlationData);
}
}
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitmqPublishDelayTopic {
@Autowired
RabbitTemplate rabbitTemplate;
public void sendTimeoutMsg(String msge , int delay, String id){
CorrelationData correlationData = new CorrelationData(id);
rabbitTemplate.convertAndSend(RabbitConst.EXCHANGE_TOPIC, RabbitConst.DELAY_QUEUES, msge, message ->{
message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
message.getMessageProperties().setDelay(delay * 1000);
return message;
},correlationData);
}
public void send(String msge, String id) {
CorrelationData correlationData = new CorrelationData(id);
this.rabbitTemplate.convertAndSend(RabbitConst.PAY_EXCHANGE_TOPIC, RabbitConst.PAY_SUCCESS_QUEUES, msge, correlationData);
}
public void sendPriority1(String msge, String id) {
CorrelationData correlationData = new CorrelationData(id);
this.rabbitTemplate.convertAndSend(RabbitConst.PRIORITY_TOPIC, RabbitConst.PRIORITY_QUEUES, msge, correlationData);
}
public void sendPriority2(String msge, String id) {
CorrelationData correlationData = new CorrelationData(id);
this.rabbitTemplate.convertAndSend(RabbitConst.PRIORITY_TOPIC_1, RabbitConst.PRIORITY_QUEUES_1, msge, correlationData);
}
}
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitmqPublishDirect {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMsg(String id, String msge){
CorrelationData correlationData = new CorrelationData(id);
rabbitTemplate.convertAndSend(RabbitConst.DEFAULT_EXCHSNGE_NAME, RabbitConst.ORDER_PAY_QUEUE_NAME , msge, correlationData);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.xiaoantimes.estimate.auth.client.annotation.IgnoreUserToken;
import com.xiaoantimes.estimate.common.msg.BaseResponse;
import com.xiaoantimes.estimate.common.util.ResBodyUtil;
import com.xiaoantimes.estimate.usercenter.mq.RabbitmqPublishDelayFanout;
import com.xiaoantimes.estimate.usercenter.mq.RabbitmqPublishDelayTopic;
import com.xiaoantimes.estimate.usercenter.mq.RabbitmqPublishDirect;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@RestController
@RequestMapping("/user/mq")
public class RabbitMqController {
@Autowired
private RabbitmqPublishDelayFanout rabbitmqPublishDelay;
@Autowired
private RabbitmqPublishDelayTopic rabbitmqPublishDelayTopic;
@Autowired
private RabbitmqPublishDirect rabbitmqPublishDirect;
@ApiOperation(value = "延时Topic", notes = "", tags = "RabbitMq", httpMethod = "GET")
@IgnoreUserToken
@GetMapping(value="/mqTopicDelayed")
public BaseResponse mqTopicDelayed(@ApiParam(required = true, value = "发送mq内容") @RequestParam String msge,
@ApiParam(required = true, value = "延时时间") @RequestParam Integer time,
@ApiParam(required = true, value = "消息发送mq成功或失败消息id") @RequestParam String id){
rabbitmqPublishDelayTopic.sendTimeoutMsg(msge, time, id);
return ResBodyUtil.buildSuccessResBody();
}
@ApiOperation(value = "普通发送Topic", notes = "", tags = "RabbitMq", httpMethod = "GET")
@IgnoreUserToken
@GetMapping(value="/mqTopicOrdinary")
public BaseResponse ordinary(@ApiParam(required = true, value = "发送mq内容") @RequestParam String msge,
@ApiParam(required = true, value = "消息发送mq成功或失败消息id") @RequestParam String id){
rabbitmqPublishDelayTopic.send( msge,id);
return ResBodyUtil.buildSuccessResBody();
}
@ApiOperation(value = "优先级队列Topic", notes = "", tags = "RabbitMq", httpMethod = "GET")
@IgnoreUserToken
@GetMapping(value="/mqTopicPriority")
public BaseResponse mqTopicPriority(@ApiParam(required = true, value = "发送mq内容") @RequestParam String msge,
@ApiParam(required = true, value = "消息发送mq成功或失败消息id") @RequestParam String id){
rabbitmqPublishDelayTopic.sendPriority1( msge, id);
return ResBodyUtil.buildSuccessResBody();
}
@ApiOperation(value = "优先级队列Topic", notes = "", tags = "RabbitMq", httpMethod = "GET")
@IgnoreUserToken
@GetMapping(value="/mqTopicPriority2")
public BaseResponse mqTopicPriority2(@ApiParam(required = true, value = "发送mq内容")@RequestParam String msge,
@ApiParam(required = true, value = "消息发送mq成功或失败消息id") @RequestParam String id){
rabbitmqPublishDelayTopic.sendPriority2(msge, id);
return ResBodyUtil.buildSuccessResBody();
}
@ApiOperation(value = "普通Direct", notes = "", tags = "RabbitMq", httpMethod = "GET")
@IgnoreUserToken
@GetMapping(value="/mqDirectOrdinary")
public BaseResponse mqDirectOrdinary(
@ApiParam(required = true, value = "消息发送mq成功或失败消息id") @RequestParam String id,
@ApiParam(required = true, value = "发送mq内容") @RequestParam String msge){
rabbitmqPublishDirect.sendMsg(id, msge);
return ResBodyUtil.buildSuccessResBody();
}
@ApiOperation(value = "延时Fanout", notes = "", tags = "RabbitMq", httpMethod = "GET")
@IgnoreUserToken
@GetMapping(value="/fanoutDelayed")
public BaseResponse fanoutDelayed(@ApiParam(required = true, value = "发送mq内容") @RequestParam String msge,
@ApiParam(required = true, value = "延时时间") @RequestParam Integer time,
@ApiParam(required = true, value = "消息发送mq成功或失败消息id") @RequestParam String id){
rabbitmqPublishDelay.sendTimeoutMsg(msge, time, id);
return ResBodyUtil.buildSuccessResBody();
}
}
配置文件
spring:
rabbitmq:
password: guest
username: guest
port: 5672
addresses: 10.10.0.198
#开启发送失败返回
publisher-returns: true
#开启发送确认
publisher-confirms: true
listener:
simple:
#指定最小的消费者数量.
concurrency: 2
#指定最大的消费者数量.
max-concurrency: 2
#开启ack
acknowledge-mode: manual
#开启ack
direct:
acknowledge-mode: auto
#支持消息的确认与返回
template:
mandatory: true
pom文件添加
<!-- RabbitMQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>