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

Implement Caching in Apache Shiro using JBoss Infinspan

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

你需要实现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.Cache经理

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));
    }

}

注入缓存容器。如果您的领域启用了 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中使用其他缓存框架实现它。