Caffeine缓存访问时出现ClassCastException问题求助
问题排查:String无法转换为AppConfiguration异常
执行以下代码时:
AppConfigurationCacheService appCache = getAppContext().getBean("appConfigurationCacheService"); appCache.getAppConfig("LANDING_PAGE");
抛出异常:
java.lang.String cannot be cast to my.daomodel.AppConfiguration: java.lang.ClassCastException: java.lang.String cannot be cast to my.daomodel.AppConfiguration at my.service.cache.AppConfigurationCacheService$$EnhancerBySpringCGLI$$8a364268.getAppConfig(<generated>)
将getAppConfig方法返回值改为String后异常消失,怀疑缓存配置错误,相关类代码如下:
实体类代码
@Component @Entity @Table(name="APP_CONFIGURATION") @SuppressWarnings("serial") public class AppConfiguration implements Serializable{ @Id @SequenceGenerator(name="AppConfigIdSeq", sequenceName="APP_CONFIG_ID_SEQ", initialValue=1, allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="AppConfigIdSeq") @Column(name="APP_CONFIG_ID", nullable=false) private long appConfigId; @Column(name="CONFIG_KEY", nullable=false) @Type(type="string") private String configKey; @Column(name="CONFIG_VALUE") @Type(type="string") private String configValue; public AppConfiguration(){ } public long getAppConfigId(){ return appConfigId; } public void setAppConfigId(long appConfigId){ this.appConfigId = appConfigId; } public String getConfigKey(){ return configKey; } public void setConfigKey(String configKey){ this.configKey = configKey; } public String getConfigValue(){ return configValue; } public void setConfigValue(String configValue) { this.configValue = configValue; } }
缓存管理器代码
@Configuration @EnableCaching public class CaffeineCacheManager extends CachingConfigurerSupport{ @Bean public CacheManager cacheManager(){ CaffeineCacheManager cacheManager = new CaffeinieCacheManager("appConfigCache"); cacheManager.setCaffeine( Caffeine.newBuilder() .initialCapacity(300) .maximumSize(1000) .recordStats() ); return cacheManager; } }
缓存服务类代码
@Service @CacheConfig(cacheName={"appConfigCache"}) public class AppConfigurationCacheService{ @Autowired private AppConfigurationDao appConfigurationDao; @Cacheable(key="#configKey") public AppConfiguration getAppConfig(String configKey){ AppConfiguration appConfig = appConfigurationDao.getAppConfigurationByKey(configKey); return appConfig; } }
排查步骤及解决方案
清理缓存中的旧数据
可能之前有其他逻辑向appConfigCache中存入了String类型的LANDING_PAGE键值,Spring Cache命中后直接返回缓存值导致类型不匹配。- 解决:重启应用清空本地缓存,或调用缓存清除接口手动清理
appConfigCache。
- 解决:重启应用清空本地缓存,或调用缓存清除接口手动清理
修正缓存管理器拼写错误
缓存管理器代码中new CaffeinieCacheManager("appConfigCache")存在拼写错误,正确类名为CaffeineCacheManager。该错误会导致缓存管理器初始化异常,可能触发默认缓存逻辑,引发类型存储错误。- 解决:修正拼写后重启应用测试。
验证DAO层返回值类型
检查AppConfigurationDao.getAppConfigurationByKey(configKey)的实际返回结果,确认是否在某些场景下错误返回了configValue(String类型)而非完整的AppConfiguration对象。首次调用时DAO返回String会被缓存,后续请求直接命中错误类型。- 解决:调试DAO方法,检查SQL映射是否正确,确保返回实体类实例。
明确缓存注解配置
当前@Cacheable未指定cacheNames,可能和其他缓存空间冲突。- 解决:修改注解为
@Cacheable(cacheNames = "appConfigCache", key = "#configKey"),明确缓存空间。
- 解决:修改注解为
内容的提问来源于stack exchange,提问作者T.J
相关产品推荐
相关产品推荐

