【问题标题】:Spring custom annotation for caching用于缓存的 Spring 自定义注解
【发布时间】:2013-06-13 14:42:47
【问题描述】:

我使用了基于 Spring 声明式注释的缓存方法。这是我的使用方法,

@Cacheable(value = "users", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getName().concat(#username)")
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException { //method body }

这个注释看起来很长。我尝试使用自定义键生成器,但问题是当我在注释中定义键时,自定义键生成器不会被调用。

所以现在我尝试使用自定义弹簧注释作为解决方法。但我无法找到一个好的参考来开始。基本上我需要为键(租户标识符)添加一个上下文感知参数。

任何帮助将不胜感激。

【问题讨论】:

  • 你检查过 using custom annotations 上的 Spring 文档吗?
  • @dimchez 是的。但在我的情况下,需要通过向键添加上下文感知参数来更改每个键。自定义注释上的 Spring 文档没有提供有关如何执行此类操作的详细信息。
  • 如果您不想全部使用,您可以使用自定义密钥生成器并注释要用于密钥生成的方法的参数。

标签: spring caching annotations


【解决方案1】:

Key 必须是静态变量。它不能是运行时评估。 您需要覆盖 CacheManager 然后进行修改。下面是我扩展 HazelcastCacheManager 的示例,它又扩展了 spring 的 Cachemanager

public class MyCache extends HazelcastCacheManager {

    private final ConcurrentMap<String, Cache> myCaches = new ConcurrentHashMap<String, Cache>();

    public MyCache(){
        super();
    }


    public MyCache(HazelcastInstance hazelcastInstance){
        super(hazelcastInstance);
    }
    @Override
    public Cache getCache(String name) {

        String tenant = org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getName();
        Cache cache = myCaches.get(tenant.concat("#").concat(name));
        if (cache == null) {
            IMap<Object, Object> map = getHazelcastInstance().getMap(tenant.concat("#").concat(name));
            cache = new HazelcastCache(map);
            Cache currentCache = cesCaches.putIfAbsent(tenant.concat("#").concat(name), cache);
            if (currentCache != null) {
                cache = currentCache;
            }
        }

        return (Cache)cache;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 2013-02-24
    • 2011-06-13
    相关资源
    最近更新 更多