最近一段时间开发工作中,发现了一些mybatis使用的技巧或注意事项,在这里总结一下。
使用Interceptor监控接口使用量
最近由于项目优化,我们需要下线几个数据表,为了安全的移除对几张数据表的依赖,下线过程分成了两个步骤:一是移除对几张表的查询依赖,二是停止对几张表的写入操作。
对几张表的操作使用了mybatis,涉及的方法较多,而且涉及业务系统的核心链路,稍有不慎可能会阻塞核心链路,导致P级故障。
在完成以上两个步骤的开发工作后,为了监控对几张表的使用情况,我们把每个表的Mapper方法访问做了日志埋点,然后基于日志信息绘制监控图表,直观查看每个方法的访问情况。这里使用的就是mybatis的拦截器(Interceptor)。
@Component
@Intercepts(value = {
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MapperMethodInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget();
if (target instanceof Executor) {
// 获取当前执行的MappedStatement
MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
// 完成的id
String id = mappedStatement.getId();
// 对应的类名
String mapperName = id.substring(0, id.lastIndexOf("."));
// 方法名
String meth