如何为spring cache(@cachable)编写自定义拦截器

时间:2017-09-28 21:46:25

标签: spring-boot spring-cache

我使用spring cache缓存数据。现在我想在写入缓存之前加密少量数据,并在读取时解密数据。那么有什么方法可以为@cachable注释编写自定义拦截器/ aop

1 个答案:

答案 0 :(得分:3)

您可以简单地为CacheCacheResolver使用装饰器来代替AOP。

public class EncodingCacheResolver implements CacheResolver {

  private final CacheResolver delegate;

  public EncodingCacheResolver(CacheResolver delegate) {
    this.delegate=delegate;
  }

  @Override
  public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {    
    Collection<Cache> result = delegate.resolveCaches(context);
    return result.stream().map(EncodingCache::new).collect(Collectors.toLlist());
  }
}

缓存实现

public class EncodingCache implements Cache {

  private final Cache delegate;

  public EncodingCache(Cache delegate) {
    this.delegate=delegate;
  }

  public String getName() {
    return delegate.getName();
  }

  public Object getNativeCache() {
    return delegate.getNativeCache();
  }

  public void evict(Object key) {
    delegate.evict(key)
  }

  public void put(Object key, Object value) {
    Object encodedValue = encode(value);
    this.delegate.put(key, encodedValue);
  }

  public <T> T get(Object key, Class<T> type) {
    Object encodedValue = delegate.get(key, type);
    return decode(encodedValue);
  }
  
  // Other Cache methods omitted but the pattern is the same 

  private Object encode(Object value) {
    // encoding logic here
  }

  private Object decode(Object value) {
    // decoding logic here
  }

}

然后进行一些配置

@Configuration
@EnableCache
public void CacheConfiguration {

  @Bean
  public CacheResolver cacheResolver(CacheManager cacheManager) {
    return new EncodingCacheResolver(SimpleCache.of(cacheManager));
  } 

}

尚未测试实现,请从我的头顶输入。但这应该或多或少是您所需要的。您真的不需要AOP。