我使用threadlocal
每个请求 sql 查询计数的静态变量存储。
作为代码
public class App {
public static ThreadLocal<Integer> count = ThreadLocal.withInitial(() -> 0);;
}
当一些 sql 执行时,我会算上它
public class P6spyListener extends JdbcEventListener {
@Override
public void onAfterExecuteQuery(PreparedStatementInformation statementInformation, long timeElapsedNanos, SQLException e) {
// System.out.println(statementInformation.getSqlWithValues());
log.info("又是这个问题.."+App.count.get().toString());
App.count.set(App.count.get() + 1);
log.info("execute query..." + statementInformation.getSqlWithValues());
}
@Override
public void onAfterExecuteUpdate(PreparedStatementInformation statementInformation, long timeElapsedNanos, int rowCount, SQLException e) {
App.count.set(App.count.get() + 1);
log.info("execute update.." + statementInformation.getSqlWithValues());
}
@Override
public void onAfterExecute(StatementInformation statementInformation, long timeElapsedNanos, String sql, SQLException e) {
App.count.set(App.count.get() + 1);
log.info("execute.." + statementInformation.getSqlWithValues());
}
}
然后我记录完成后的总数
public class RequestInitInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info(String.format("count is %d",App.count.get()));
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info(String.format("finish request... 执行sql %d ", App.count.get()));
App.count.remove();
}
}
一切都好,我可以得到成功的结果
但是当我编辑任何代码时,springboot 会自动重启。那么计数是错误的。
结果始终为零。