** 第1步:引入缓存上下文**
importcom.zhangziwa.practisesvr.model.Student;importjava.util.HashMap;importjava.util.Map;importjava.util.Objects;importstaticorg.apache.commons.lang3.ObjectUtils.anyNull;publicclassStudentContextHolder{privatestaticfinalThreadLocal<Map<Integer,Student>> studentContextHolder =ThreadLocal.withInitial(HashMap::new);publicstaticStudentgetStudent(Integer id){if(Objects.isNull(id)){returnnull;}return studentContextHolder.get().get(id);}publicstaticvoidsetStudent(Integer id,Student student){if(anyNull(id, student)){return;}if(getStudent(id)!=null){thrownewUnsupportedOperationException("Student with id "+ id +" already exists.");}
studentContextHolder.get().put(id, student);}publicstaticvoidclear(){
studentContextHolder.remove();}}
** 第2步:查询先查缓存,查询到值先存缓存**
publicStudentqueryById(Integer id){if(Objects.isNull(id)){returnnull;}// 线程缓存里去Student student =StudentContextHolder.getStudent(id);if(nonNull(student)){return student;}
student = studentsMapper.queryById(id);// 查询数据库值先存缓存StudentContextHolder.setStudent(id, student);return student;}
** 第3步:清理缓存上下文**
publicclassResponsePostInterceptorimplementsHandlerInterceptor{//在Controller执行之前调用,如果返回false,controller不执行@OverridepublicbooleanpreHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throwsException{System.err.println("***ResponsePostInterceptor.preHandle***");returntrue;}//controller执行之后,且页面渲染之前调用@OverridepublicvoidpostHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView)throwsException{System.err.println("***ResponsePostInterceptor.postHandle***");}//页面渲染之后调用,一般用于资源清理操作@OverridepublicvoidafterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex)throwsException{System.err.println("***ResponsePostInterceptor.afterCompletion***");StudentContextHolder.clear();// 清除student上下文}}
** 第4步:验证使用**
@GetMapping("{id}")publicResponseEntity<Student>queryById(@PathVariable("id")Integer id){System.out.println("***StudentController.queryById***");Student body = studentService.queryById(id);System.out.println(body);System.out.println(studentService.queryById(id));returnResponseEntity.ok(body);}
** 执行日志**
[2024-01-2601:16:16.068_068][WARN ][http-nio-8080-exec-2][LogFilter.java:21] → [LogFilter.doFilter:Start processing request at 2024-01-25T17:16:16.068132700Z -/students/8]***LogFilter.doFilter.start******RequestHeaderCheckFilter.doFilter.start******ResponsePostInterceptor.preHandle******LogInterceptor.preHandle***[2024-01-2601:16:16.094_094][WARN ][http-nio-8080-exec-2][LogInterceptor.java:37] → [LogInterceptor.postHandle:Start processing request at 2024-01-25T17:16:16.094950300Z -/students/8]***StudentController.queryById***Creating a newSqlSessionSqlSession[org.apache.ibatis.session.defaults.DefaultSqlSession@3bfba234] was not registered for synchronization because synchronization is not active
[2024-01-2601:16:16.128_128][INFO ][http-nio-8080-exec-2][HikariDataSource.java:110] → [practisedb -Starting...][2024-01-2601:16:16.248_248][INFO ][http-nio-8080-exec-2][HikariPool.java:565] → [practisedb -Added connection com.mysql.cj.jdbc.ConnectionImpl@12e4ef1][2024-01-2601:16:16.252_252][INFO ][http-nio-8080-exec-2][HikariDataSource.java:123] → [practisedb -Start completed.]
JDBC Connection[HikariProxyConnection@688850212 wrapping com.mysql.cj.jdbc.ConnectionImpl@12e4ef1] will not be managed by Spring==>Preparing: select id, username, password, age, height, gender, class_id, is_delete from students where id =?***SqlExecuteInterceptor.intercept******SqlReadRowInterceptor.intercept***==>Parameters:8(Integer)<==Columns: id, username, password, age, height, gender, class_id, is_delete
<==Row:8, 汪子韬, lq2fks1eg5,24,161.84, 女,5,0<==Total:1Closing non transactional SqlSession[org.apache.ibatis.session.defaults.DefaultSqlSession@3bfba234]Student(id=8, username=汪子韬, password=lq2fks1eg5, age=24, height=161, gender=女, classId=5, isDelete=false)Student(id=8, username=汪子韬, password=lq2fks1eg5, age=24, height=161, gender=女, classId=5, isDelete=false)***ResponsePostAdvice.supports******ResponsePostAdvice.beforeBodyWrite******LogInterceptor.postHandle******ResponsePostInterceptor.postHandle******LogInterceptor.afterCompletion***[2024-01-2601:16:16.394_394][WARN ][http-nio-8080-exec-2][LogInterceptor.java:57] → [LogInterceptor.postHandle:Finished processing request at 2024-01-25T17:16:16.393566400Z -/students/8 in 299ms. Status code:200][2024-01-2601:16:16.413_413][INFO ][http-nio-8080-exec-2][logUtils.java:70] → [{"traceId":"9287f21b215b49e19ed7fd94c9aed4e6","endDate":"2024-01-26T01:16:16.3972818+08:00[Asia/Shanghai]","cost":299,"remoteHost":"0:0:0:0:0:0:0:1","remoteAddr":"0:0:0:0:0:0:0:1","remotePort":12742,"method":"GET","requestURI":"/students/8","status":200,"requestContentLength":-1,"sqlCount":1,"sqlCost":31,"sqlSearchedRowCount":1,"currentThreadTime":109,"currentThreadUserTime":78,"currentThreadAllocatedBytes":20845224}][2024-01-2601:16:16.419_419][WARN ][http-nio-8080-exec-2][LogFilter.java:30] → [LogFilter.doFilter:Finished processing request at 2024-01-25T17:16:16.419516700Z -/students/8 in 351ms. Status code:200]***ResponsePostInterceptor.afterCompletion******RequestHeaderCheckFilter.doFilter.end******LogFilter.doFilter.end***
本文转载自: https://blog.csdn.net/weixin_37646636/article/details/135856832
版权归原作者 张紫娃 所有, 如有侵权,请联系我们删除。
版权归原作者 张紫娃 所有, 如有侵权,请联系我们删除。