<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
@Configuration
public class RabbitConfig {
@Bean
public Queue queue(){
return new Queue("api-log", true); // 持久化
}
}
@Component
@RabbitListener(queues = "api-log")
public class ApiLogMqListener {
private static final Logger logger = LoggerFactory.getLogger(ApiLogMqListener.class);
/**
* 指定消息的处理方法
*
* @param invokeLog
*/
@RabbitHandler
public void process(SysInvokeLog invokeLog) {
logger.info("接收的消息为: {}", invokeLog.toJson());
}
}
@RestController
public class RabbitController {
private static final Logger log = LoggerFactory.getLogger(RabbitController.class);
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 发送消息
*
* @param message
* @return
*/
@GetMapping(value = "/message/send")
public CommonResult sendSimpleMessage() {
try {
//发送消息
SysInvokeLog invokeLog = new SysInvokeLog();
invokeLog.setThreadName(Thread.currentThread().getName());// 当前线程
rabbitTemplate.convertAndSend("api-log", invokeLog);
} catch (Exception e) {
log.error("发送消息发生异常:{} ", e.fillInStackTrace());
}
return ResultUtils.buildSuccess();
}
}
onfig.ApiLogMqListener | 接收的消息为: {"threadName":"http-nio-8803-exec-1"}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190607190821566.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzU3NzgwMA==,size_16,color_FFFFFF,t_70)