面對數據庫查詢性能瓶頸,傳統方案需修改業務代碼引入緩存邏輯,違反開閉原則。本文展示如何利用 Spring AOP 切面編程,配合 Redis 高性能鍵值存儲,實現零侵入式查詢緩存增強。
核心邏輯:查詢請求攔截 → Redis 緩存查找 → 命中直接返回 → 未命中穿透數據庫 → 結果序列化存入 Redis → 返回數據。採用環繞通知完美契合「前置查緩存、後置存緩存」的雙向需求。
採用 Jedis 連接池管理連接資源,關鍵配置參數:
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="minIdle" value="${redis.minIdle}"/>
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxTotal" value="${redis.maxTotal}"/>
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="close">
<constructor-arg name="poolConfig" ref="poolConfig"/>
<constructor-arg name="host" value="${redis.host}"/>
<constructor-arg name="port" value="${redis.port}"/>
</bean>
為應對複雜對象結構(List、Map、嵌套對象),採用 Java 原生序列化機制,將任意對象轉為 byte[] 存儲:
public static byte[] serialize(Object obj) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
return baos.toByteArray();
}
public static Object unSerialize(byte[] bytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
@Component @Aspect
public class RedisAspect {
@Autowired @Qualifier("redisCache") private RedisCache redisCache;
@Pointcut("execution(* com.club.common.redis.service.TestService.get(java.lang.Integer)) && args(applId)")
public void myPointCut() {}
@Around("myPointCut()")
public Object around(ProceedingJoinPoint joinPoint) {
// 獲取參數構建緩存 Key
String applId = String.valueOf(joinPoint.getArgs()[0]);
String redisKey = applId;
// 前置:查詢 Redis
Object cached = redisCache.getDataFromRedis(redisKey);
if (cached != null) return cached;
// 執行目標方法(查詢數據庫)
Object result = joinPoint.proceed();
// 後置:存入 Redis
redisCache.setDataToRedis(redisKey, result);
return result;
}
}
實際項目中針對 Key 衝突問題,採用「applId:全限定類名.方法名」複合鍵策略;切點表達式使用 || 組合多業務入口。測試數據顯示:複雜 SQL(688 行)查詢從 10 秒降至 2 秒內,性能提升 80%。
此方案最大優勢在於完全不修改現有業務代碼,通過配置切點即可擴展至任意查詢方法,體現了 AOP 「關注點分離」的核心價值。