pom.xml中依赖:
<!-- 消息队列 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.yml中配置关于RabbitMQ的连接和用户信息:
rabbitmq:
host: localhost
port: 5672
username: springcloud
password: 123456
listener:
#最小消息监听线程数
concurrency: 2
#最大消息监听线程数
max-concurrency: 2
实现发送消息的方法,AmqpTemplate接口定义了一套针对AMQP协议的基础操作
package com.techlutong.jzm.rabbitmq;
import com.techlutong.jzm.constant.RabbitConfigConstant;
import com.techlutong.jzm.model.JzmUserVisitor;
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;
/**
*
* @Description mq 发送
* @Date 2019/3/1 14:39
* @Param
* @return
**/
@Component
public class RabbitMqSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendJzmUserVisitorMq(JzmUserVisitor jzmUserVisitor) {
CorrelationData correlationSendData=new CorrelationData();
this.rabbitTemplate.convertAndSend(RabbitConfigConstant.JzmUserVisitorRabbitConfig.TOPIC_EXCHANGE, RabbitConfigConstant.JzmUserVisitorRabbitConfig.ROUTE_KEY,
//消息体内容
jzmUserVisitor,
//correlationSendData消息的唯一id
correlationSendData
);
}
}
接受消息的方法类,并用@RabbitHandler注解来指定对消息的处理方法。
package com.techlutong.jzm.rabbitmq;
import com.rabbitmq.client.Channel;
import com.techlutong.jzm.constant.RabbitConfigConstant;
import com.techlutong.jzm.model.JzmUserVisitor;
import com.techlutong.jzm.service.JzmUserVisitorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
*
* @Description 监听 mq 接收消息
* @Param
* @return
**/
@Component
public class RabbitMqReceiver {
@Autowired
JzmUserVisitorService jzmUserVisitorService;
private static final Logger logger = LoggerFactory.getLogger(RabbitMqReceiver.class);
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitConfigConstant.JzmUserVisitorRabbitConfig.QUEUE, durable = "true"), exchange = @Exchange(value = RabbitConfigConstant.JzmUserVisitorRabbitConfig.TOPIC_EXCHANGE, type = ExchangeTypes.TOPIC), key = RabbitConfigConstant.JzmUserVisitorRabbitConfig.ROUTE_KEY))
@RabbitHandler
public void jzmUserVisitorMqSuccReceiver(@Payload JzmUserVisitor jzmUserVisitor, @Headers Map<String,Object> headers, Channel channel) throws Exception {
jzmUserVisitorService.saveUserVisitor(jzmUserVisitor);
}
}