Reputation: 57
I use a static threadlocal
variable store per request sql query count.
As the code
public class App {
public static ThreadLocal<Integer> count = ThreadLocal.withInitial(() -> 0);;
}
And i count it when some sql execute
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());
}
}
then i log the total count afterCompletion
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();
}
}
everything right,i can get success result
But when i edit anycode ,the springboot auto restart. then count is wrong.
the result always is zero.
Upvotes: 0
Views: 283