springboot(25)ehcache读取缓存ClassCastException
现象
本地IDE使用redis+ehcache缓存时,读取缓存抛出如下异常。明明是用一个类型,却发生A cannot be cast to A
的ClassCastException的异常,实在是令人摸不着头脑。
1 | java.lang.ClassCastException: com.cardinfolink.saber.marketing.model.BenefitRecord cannot be cast to com.cardinfolink.saber.marketing.model.BenefitRecord |
分析
This is a known limitation of Devtools. When the cache entry is deserialized, the object is not attached to the proper classloader.
There are various ways you can fix this issue:
- Disable cache when you’re running your application in development
- Use a different cache manager (if you’re using Spring Boot 1.3, you could force a
simple
cache manager using thespring.cache.type
property inapplication-dev.properties
and enable the dev profile in your IDE)- Configure memcached (and things that are cached) to run in the application classloader. I wouldn’t recommend that option since the two first above are much easier to implement
当使用SpringBoot的DevTools用于热加载时,首先类加载器为A,对象被序列化到缓存。修改代码导致热加载后,DevTools重新创建了类加载器B。然后出现错误的类加载器加载对象导致A cannot be cast to A
的异常。
解决
最简单无脑的方式就是删除DevTools的依赖。
1 | <dependency> |