springboot+rabbitMq存储⽇志到数据库
“⽌于唇齿的热爱最廉价,如果不是⼀起到最后的那个⼈,那⼀个⼈⼀辈⼦⼜有何妨“”
概述
spring提供了AmqpTemplate使⽤rabbitmq,使⽤起来⾮常的⽅便,有关rabbitmq的介绍⽹上已经有了很多很好的⽂章开始搬砖
implementation('org.springframework.boot:spring-boot-starter-amqp')
maven项⽬⾃⼰转⼀下
配置
spring:
rabbitmq:
# 虚拟机
virtual-host: xxx
# 路径()
host: rabbitmq.byb
port:5672
username: xxx
password: xxx
listener:
simple:
# 初始化并发数量
concurrency:10
# 设置并发最⼤数量
max-concurrency:20
初始化队列
@Configuration
public class MQConfig {
public static final String BIZLOG_QUEUE ="bizlog";
@Bean
public Queue bizLogQueue(){
return new Queue(BIZLOG_QUEUE ,true);
}
当mq中不存在定义的队列时会⾃动创建
需要使⽤交换机时可以在这⾥定义和绑定,定义和队列⼀样,名字改⼀下就可以,绑定定义⼀个binding
⾥⾯是需要的参数,我没有使⽤,会不会出问题还不知道,可以参考其他⽂章
发送消息到rabbitmq
Boolean data =(Boolean) vertSendAndReceive("bopLog", JSONString(map));
json使⽤的是阿⾥巴巴的fastjson
因为我是⼀条消息只需要存到⼀个数据库,也就是⼀个队列对应⼀个数据库,所以我不需要使⽤交换机,如果需要⼀条消息存到不同的数据库,可以定义⼀个交换机,⽅法还是这个⽅法,更改传⼊的参数为exchange和rootkey,将队列绑定到交换机即可。
发送的⽅法有很多,我主要使⽤了converAndSend和convertSendAndReceive,converAndSend是直接发送,没有返
回,converSendAndReceive是发送和接受返回,如果成功接受则会返回true,失败则返回空,缺点就是可能会有点慢,⽽且有⼀定的耦合,个⼈建议,在开发时使⽤converSendAndReceive,调试时可以很快的知道是接受出了问题还是发送出了问题,当所有的都调通之后可以改为converAndSend,这样他只需要发送到mq,不管你是否接受成功,这样降低了耦合,即使监听接受的服务宕机了,下次开机时⼀样可以将数据存储到数据库
接受并保存到数据库
发送和接受完全可以定义在不同的项⽬,他们之间并⽆直接的联系
@Component
public class BopReceiver {
private Logger logger = Logger(BopReceiver.class);
@Autowired
ListenerUtil listenerUtil;
/**
* <p>⽅法描述:监听消息队列存储数据到数库 </p >
* @param message ⽇志消息
* @author zlh
* @since 2019/9/19 11:32
* @return
*/
@RabbitListener(queues ="bopLog")
public Boolean listenerBopLog(String message){
String tableName ="log_bop";
Boolean bopLog = listenerUtil.lister(message, tableName, logger,"存储业务⽇志失败");
return bopLog;
}
public Boolean lister(String message, String tableName, Logger logger,String errorMsg){
Boolean bool = null;
String uuid =getUUID();
try{
Map map = JSON.parseObject(message, Map.class);
//我⾃⼰的处理,删掉
map =findName(map);
springboot aopmap.put("id", uuid);
//存⼊数据库
bool = DbHelper.use("log").insert(tableName, map);
}catch(Exception e){
e.printStackTrace();
<(errorMsg);
}
return bool;
}
我这⾥做了⼀些处理,如果你不需要做处理直接将message转为map存⼊数据库就可以。
如果是访问⽇志的话可以写⼀个aop切⾯,再写⼀个注解,使⽤注解会很⽅便。需要的话⾃⼰去查吧。。