package com.zy.asrs.wms.common.interceptor; import com.zy.asrs.framework.common.SpringUtils; import com.zy.asrs.wms.common.constant.RedisConstants; import com.zy.asrs.wms.utils.RedisUtil; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.plugin.*; import java.sql.Connection; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}) }) public class DataChangeInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); String sql = statementHandler.getBoundSql().getSql(); if (sql != null) { String trimmedSql = sql.trim().toUpperCase(); // System.out.println("SQL: " + sql); if (trimmedSql.startsWith("INSERT")) { clearRedisCache(trimmedSql); } else if (trimmedSql.startsWith("UPDATE")) { clearRedisCache(trimmedSql); } else if (trimmedSql.startsWith("DELETE")) { clearRedisCache(trimmedSql); } } // 根据需要进行SQL解析 return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) {} public static String extractTableName(String sql) { if (sql == null || sql.trim().isEmpty()) { return "无效的SQL语句"; } String trimmedSql = sql.trim().toUpperCase(); String tableName = ""; // 定义正则表达式 Pattern insertPattern = Pattern.compile("INSERT INTO (\\S+)", Pattern.CASE_INSENSITIVE); Pattern updatePattern = Pattern.compile("UPDATE (\\S+)", Pattern.CASE_INSENSITIVE); Pattern deletePattern = Pattern.compile("DELETE FROM (\\S+)", Pattern.CASE_INSENSITIVE); Matcher matcher; // 检查INSERT语句 matcher = insertPattern.matcher(trimmedSql); if (matcher.find()) { tableName = matcher.group(1); } else { // 检查UPDATE语句 matcher = updatePattern.matcher(trimmedSql); if (matcher.find()) { tableName = matcher.group(1); } else { // 检查DELETE语句 matcher = deletePattern.matcher(trimmedSql); if (matcher.find()) { tableName = matcher.group(1); } } } if (tableName.isEmpty()) { return null; } return tableName; } private void clearRedisCache(String sql) { RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class); if (redisUtil == null) { return; } String tableName = extractTableName(sql); if (tableName == null) { return; } tableName = tableName.toLowerCase(); Set keys = redisUtil.searchRedisKeys(tableName); for (String key : keys) { if (!key.startsWith(RedisConstants.CACHE_DATA)) { continue; } redisUtil.del(key); } } }