【问题标题】:Implement Guava cache as a fallback for EHCache实现 Guava 缓存作为 EHCache 的后备
【发布时间】:2021-07-30 23:19:32
【问题描述】:

我想在我的 springboot 应用程序中实现 Guava 缓存作为 EHcache 2.10 的后备。如果 EH 缓存以某种方式失败或崩溃,系统必须回退到 Guava 缓存并获取结果。请指导我如何操作。

【问题讨论】:

    标签: spring-boot jpa caching guava ehcache


    【解决方案1】:

    在这种情况下,可以使用**内置**注解,以便您可以自行检查和构建所有逻辑。

    你总是可以定义 DAO(Data Access Object) 层,这将与 EHCahe 和 Guava 缓存进行通信。

    interface UserDao{
       Optional<User> findById(int id);
       ...
    }
    

    实现 UserDao

    class UserDaoImpl implements UserDao {
        @Autowired  @Qualifier("ehCacheManager") private CacheManager ehCacheManager;
        @Autowired  @Qualifier("cacheManager") private CacheManager cacheManager;
        @Autowired  UserRepository userRepository;
        private Cache ehCache;
        private Cache guavaCache;
        @PostConstruct
        public void init(){
            ehCache = ehCacheManager.get("userCache");
            guavaCache = cacheManager.get("userCache");
        }
    
        @Override
        public Optional<User> findById(int id){
             User user = null;
             boolean ehCacheError;
             try{
                user = ehCache.get(id, User.class);
             } catch (Exception e){
                 user = guavaCache.get(id, User.class);
                 ehCacheError = true;
             }
             if( user == null ){
              // query db to fetch User as all cache has miss
               Optional<User> optUser = userRepository.findById( id );
               if(optUser. isPresent()){
                  user = optUser.get();
               }
               // cache miss
               if(!ehCacheError){
                   ehCache.put( id, user) ;
                   guavaCache.put(id, user);
               }
             }
             return Optional.ofNullable(user);
        }
        
    }
    

    一个奇怪的问题,你为什么要反向,你应该总是执行 Guava 缓存查找,如果有缓存未命中,你应该咨询 EHCache,这里你应该添加一个失败案例来查询 db。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多