项目场景:用Redis实现Mybatis的二级缓存
问题描述
项目使用Redis作为Mybatis的缓存,实现了org.apache.ibatis.cache.Cache
接口。
并在mapper上使用了org.apache.ibatis.annotations.CacheNamespace
接口。查询数据库时,mybatis sqlsession 执行plugin时会触发cache CacheExecutor,从而走自定义的缓存。
其中RedisTemplate
的valueSerilizer使用了FastJsonRedisSerializer
。
package org.apache.ibatis.executor;
public class CachingExecutor implements Executor {
}
原因分析:
问题是在调用selectById的时候,由于没有设置类,查询回来的数据是JSONObject.class,在接口返回时会发生强制转换。报JSONObject cannot be cast to xxxx.class
T selectById(Serializable id);
解决方案:
解决方法
将redidsTemplate的valueSerilizer 使用的 FastJsonRedisSerializer替换为GenericFastJsonRedisSerializer,这样在缓存时的json有了@type属性,在redis读取时外层是JSONArray,但里面的泛型已经是对应的@type类型
[{"@type":"com.bbb.ccc.ddd.bean.entity.entity","answerJson":Set["1"],"key":"testtest","createTime":"2022-11-03T18:07:22","id":6290,"sensitiveWord":"1234","synonymsJson":Set["123"],"updateTime":"2022-11-15T18:30:45"}]