如何为Spring Cache编写自定义拦截器(@cachable)

pbgvytdp  于 2023-03-23  发布在  Spring
关注(0)|答案(1)|浏览(151)

我正在使用Spring Cache缓存数据。现在我想在写入缓存之前加密一些数据,并在阅读时解密数据。那么有什么方法可以为@cachable annotation编写自定义拦截器/aop吗

kmbjn2e3

kmbjn2e31#

不使用AOP,您可以简单地为CacheCacheResolver使用装饰器。

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来实现它。

相关问题