how to prevent a return value from cache to be changed in spring cacheable

后端 未结 3 662
执念已碎
执念已碎 2021-01-03 12:24

i\'m working around spring 3.1 annotation cache with ehcache as a cache implement.

a method with return value like this

@Cacheable(\"cache\")
public          


        
3条回答
  •  攒了一身酷
    2021-01-03 12:45

    I had the same problem with the spring cache. I didn't want to receive the same java objects from the cache.

    In my case i want to cache big java objects with many fields and so on. So it is very painful to copy all the data classes with deep copy. I read the article about copy java objects with serialization.

    http://www.javaworld.com/article/2077578/learn-java/java-tip-76--an-alternative-to-the-deep-copy-technique.html

    This brought me to the idea to cache only the serialized data. Every time a object is read from the cache it is deserialized.

    For the serialization i used apache commons helper methods

    @Override
    public SerializedQuestions readUserQuestion(UID questionId, Locale locale) {
     byte[] serializedData = readCachedUserQuestion(questionId, locale);
     Object deserializedobject = org.apache.commons.lang.SerializationUtils.deserialize(serializedData);
     return (SerializedQuestions) deserialize;
    }
    
    @Override
    @Cacheable(value = SpringCacheKeys.USER_QUESTION_CACHE)
      public byte[] readCachedUserQuestion(UID questionId, Locale locale) {
    
      //read object from db
      SerializedQuestions questions = new SerializedQuestions()
    
      return org.apache.commons.lang.SerializationUtils.serialize(questions);
    }
    

    It depends on the spring configuration if the call to readCachedUserQuestion could be in the same class or not. Per default only extern calls to a method are cached.

提交回复
热议问题