异常java.io.InvalidClassException Java对象反序列化失败

java.io.InvalidClassException: com.xxx.yyy.bean.FlightComfortHistory; local class incompatible: stream classdesc serialVersionUID = -5421295868054627327, local class serialVersionUID = 4801854336781333672
        at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:617) ~[na:1.7.0_45]
        at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1622) ~[na:1.7.0_45]
        at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517) ~[na:1.7.0_45]
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771) ~[na:1.7.0_45]
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350) ~[na:1.7.0_45]
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) ~[na:1.7.0_45]
        at java.util.ArrayList.readObject(ArrayList.java:771) ~[na:1.7.0_45]
        at sun.reflect.GeneratedMethodAccessor75.invoke(Unknown Source) ~[na:na]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_45]
        at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_45]
--
        at com.xxx.yyy.service.RedisService.decompress(RedisService.java:200) ~[RedisService.class:na]
        at com.xxx.yyy.service.RedisService.getFlightComfortHistory(RedisService.java:66) ~[RedisService.class:na]
        at com.xxx.yyy.service.FlightComfortService.generateNationWithHistoryWithAv(FlightComfortService.java:482) ~[FlightComfortService.class:na]
        at com.xxx.yyy.service.FlightComfortService.access$000(FlightComfortService.java:66) ~[FlightComfortService.class:na]
        at com.xxx.yyy.service.FlightComfortService$GenerateNationComfortByHistoryTask.run(FlightComfortService.java:831) ~[FlightComfortService$GenerateNationComfortByHistoryTask.class:na]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_45]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_45]
        at java.lang.Thread.run(Thread.java:744) [na:1.7.0_45]

异常描述:

新代码在FlightComfortHistory类中加了一个新字段,测试时候新数据存取都是没问题的。

但是上线后发现,redis中的老数据反序列化时会报异常。

 

异常原因:

老版本代码中,FlightComfortHistory这个类实现了Serializable接口,却没有指定serialVersionUID

序列化时该类的serialVersionUID是JVM根据类名及其属性的哈希值生成的。

当类的属性有变动时,serialVersionUID也会相应变动,从而导致redis中的老数据反序列化为FlightComfortHistory对象时,serialVersionUID匹配不上而失败

 

异常解决:

1、如果不考虑新老数据兼容问题,可以直接用IDEA给类自动生成一个serialVersionUID(光标放在类名上alter/option + enter)

2、如果考虑数据兼容,找到老数据的serialVersionUID。

比如本次异常中,stream classdesc serialVersionUID = -5421295868054627327

就表示redis中现存的序列化对象的serialVersionUID为-5421295868054627327,我们只要将该类的serialVersionUID手动设为-5421295868054627327L 就行

示例

 

教训:

请务必记得给需要序列化的类生成一个serialVersionUID,不然不知道什么时候就会踢你一脚!

你可能感兴趣的:(遇到过的坑)