使用JBoss Infinspan在Apache Shiro中实现缓存

时间:2016-07-19 07:00:25

标签: java shiro infinispan

我在项目中使用Apache shiro来实现安全性。我已经使用CDI注入了安全领域。我想使用Jboss Infinispan在shiro中实现身份验证和授权缓存。有人可以分享一些指示吗?

1 个答案:

答案 0 :(得分:0)

您需要实现org.apache.shiro.cache.Cache和org.apache.shiro.cache.CacheManager以在shiro中实现缓存。如果您想使用infinispan,请按照以下步骤操作:

实施org.apache.shiro.cache.Cache

import java.util.Collection;
import java.util.Set;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;


public class InfinispanCache<K, V> implements Cache<K, V> {


    private final org.infinispan.Cache<K, V> cacheProxy;

    public InfinispanCache(final org.infinispan.Cache<K, V> cacheProxy) {
        this.cacheProxy = cacheProxy;
    }


    @Override
    public V get(final K key) throws CacheException {
        return cacheProxy.get(key);
    }


    @Override
    public V put(final K key, final V value) throws CacheException {
        return cacheProxy.put(key, value);
    }


    @Override
    public V remove(final K key) throws CacheException {
        return cacheProxy.remove(key);
    }


    @Override
    public void clear() throws CacheException {
        cacheProxy.clear();
    }


    @Override
    public int size() {
        return cacheProxy.size();
    }


    @Override
    public Set<K> keys() {
        return cacheProxy.keySet();
    }


    @Override
    public Collection<V> values() {
        return cacheProxy.values();
    }

}

实施org.apache.shiro.cache.CacheManager

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.infinispan.manager.CacheContainer;


public class InfinispanCacheManager implements CacheManager {


    private final CacheContainer cacheContainer;

    public InfinispanCacheManager(final CacheContainer cacheContainer) {
        this.cacheContainer = cacheContainer;
    }

    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public <K, V> Cache<K, V> getCache(final String name) throws CacheException {
        return new InfinispanCache(cacheContainer.getCache(name));
    }

}

注入缓存容器。如果您的Realm已启用CDI,它应该可以工作。

import javax.annotation.Resource;

 /** The security cache manager. */
    @Resource(lookup = "java:jboss/infinispan/container/<YOUR CACHE CONTAINER NAME>")
    private EmbeddedCacheManager securityCacheManager;

在领域实施中设置缓存管理器:

setCachingEnabled(true);
setAuthenticationCachingEnabled(true);
setAuthorizationCachingEnabled(true);
setCacheManager(new InfinispanCacheManager(securityCacheManager));
setAuthenticationCacheName(authenticationCacheName);
setAuthorizationCacheName(authorizationCacheName);

同样,您可以在Shiro中使用其他缓存frameworsk实现它。