Java Code Examples for org.infinispan.manager.EmbeddedCacheManager#getCache()

The following examples show how to use org.infinispan.manager.EmbeddedCacheManager#getCache() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InfinispanCacheFactory.java    From cache2k-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
protected <K, V> BenchmarkCache<K, V> createSpecialized(final Class<K> _keyType, final Class<V> _valueType, final int _maxElements) {
  EmbeddedCacheManager m = getCacheMangaer();
  ConfigurationBuilder cb = new ConfigurationBuilder();

  cb.eviction().maxEntries(_maxElements);
  cb.storeAsBinary().disable();
  if (!withExpiry) {
    cb.expiration().disableReaper().lifespan(-1);
  } else {
    cb.expiration().lifespan(5 * 60, TimeUnit.SECONDS);
  }
  switch (algorithm) {
    case LRU: cb.eviction().strategy(EvictionStrategy.LRU); break;
    case LIRS: cb.eviction().strategy(EvictionStrategy.LIRS); break;
    case UNORDERED: cb.eviction().strategy(EvictionStrategy.UNORDERED); break;
  }
  m.defineConfiguration(CACHE_NAME, cb.build());
  Cache<Integer, Integer> _cache = m.getCache(CACHE_NAME);
  return new MyBenchmarkCache(_cache);

}
 
Example 2
Source File: MyResource.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@GET
@Produces("text/plain")
public String get() throws Exception {
    EmbeddedCacheManager cacheContainer
            = (EmbeddedCacheManager) new InitialContext().lookup("java:jboss/infinispan/container/server");
    Cache<String,String> cache = cacheContainer.getCache("default");
    if (cache.keySet().contains(key)) {
        return (String) cache.get(key);
    }

    String result = UUID.randomUUID().toString();
    cache.put(key, result);
    return result;
}
 
Example 3
Source File: ClusterManager.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<R> apply(EmbeddedCacheManager cacheManager) {
    org.infinispan.Cache<K, V> cache = cacheManager.getCache(cacheName, false);
    if (cache == null) {
        return Optional.empty();
    }
    V value = cache.get(key);
    if (value == null) {
        return Optional.empty();
    }
    return Optional.ofNullable(task.apply(value));
}
 
Example 4
Source File: ConcurrencyJDGCachePutTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static Worker createWorker(int threadId) {
    EmbeddedCacheManager manager = new TestCacheManagerFactory().createManager(threadId, InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, RemoteStoreConfigurationBuilder.class);
    Cache<String, Integer> cache = manager.getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);

    System.out.println("Retrieved cache: " + threadId);

    RemoteStore remoteStore = cache.getAdvancedCache().getComponentRegistry().getComponent(PersistenceManager.class).getStores(RemoteStore.class).iterator().next();
    HotRodListener listener = new HotRodListener();
    remoteStore.getRemoteCache().addClientListener(listener);

    return new Worker(cache, threadId);
}
 
Example 5
Source File: ConcurrencyJDGRemoteCacheClientListenersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static Worker createWorker(int threadId) {
    EmbeddedCacheManager manager = new TestCacheManagerFactory().createManager(threadId, InfinispanConnectionProvider.WORK_CACHE_NAME, RemoteStoreConfigurationBuilder.class);
    Cache<String, Integer> cache = manager.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);

    System.out.println("Retrieved cache: " + threadId);

    RemoteStore remoteStore = cache.getAdvancedCache().getComponentRegistry().getComponent(PersistenceManager.class).getStores(RemoteStore.class).iterator().next();
    HotRodListener listener = new HotRodListener(cache, threadId);
    remoteStore.getRemoteCache().addClientListener(listener);

    return new Worker(cache, threadId);
}
 
Example 6
Source File: InfinispanLightminServerLockManager.java    From spring-batch-lightmin with Apache License 2.0 4 votes vote down vote up
public InfinispanLightminServerLockManager(final EmbeddedCacheManager embeddedCacheManager) {
    this.clusteredLockManager = EmbeddedClusteredLockManagerFactory.from(embeddedCacheManager);
    this.verificationCache = embeddedCacheManager.getCache(VERIFICATION_CACHE_NAME);
}
 
Example 7
Source File: ClusteredCacheBehaviorTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testListener() throws Exception {
    EmbeddedCacheManager node1 = createManager();
    EmbeddedCacheManager node2 = createManager();
    Cache<String, Object> node1Cache = node1.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
    node1Cache.addListener(new CacheListener("node1"));
    Cache<String, Object> node2Cache = node2.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
    node2Cache.addListener(new CacheListener("node2"));

    System.out.println("node1 create entry");
    node1Cache.put("key", "node1");

    System.out.println("node1 create entry");
    node1Cache.put("key", "node111");

    System.out.println("node2 create entry");
    node2Cache.put("key", "node2");

    System.out.println("node1 remove entry");
    node1Cache.remove("key");

    System.out.println("node2 remove entry");
    node2Cache.remove("key");

    System.out.println("node2 put entry");
    node2Cache.put("key", "node2");
    System.out.println("node2 evict entry");
    node2Cache.evict("key");
    System.out.println("node1/node2 putExternal entry");
    node1Cache.putForExternalRead("key", "common");
    node2Cache.putForExternalRead("key", "common");
    System.out.println("node2 remove entry");
    node2Cache.remove("key");
    System.out.println("node1 remove entry");
    node1Cache.remove("key");

    // test remove non-existing node 2, existing node 1
    System.out.println("Test non existent remove");
    System.out.println("node1 create entry");
    node1Cache.put("key", "value");
    System.out.println("node2 remove non-existent entry");
    System.out.println("exists?: " + node2Cache.containsKey("key"));
    node2Cache.remove("key");

    // test clear
    System.out.println("Test clear cache");
    System.out.println("add key to node 1, key2 to node2");
    node1Cache.putForExternalRead("key", "value");
    node2Cache.putForExternalRead("key", "value");
    node2Cache.putForExternalRead("key2", "value");
    System.out.println("Clear from node1");
    node1Cache.clear();
    System.out.println("node 2 exists key2?: " + node2Cache.containsKey("key2"));
    System.out.println("node 2 exists key?: " + node2Cache.containsKey("key"));



}
 
Example 8
Source File: L1SerializationIssueTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testL1Bug() throws Exception {
    EmbeddedCacheManager node1 = null;
    EmbeddedCacheManager node2 = null;
    EmbeddedCacheManager node3 = null;

    try {

        node1 = createManager();
        Cache<String, Object> node1Cache = node1.getCache(CACHE_NAME);
        logger.info("Node1Cache started");

        node2 = createManager();
        Cache<String, Object> node2Cache = node2.getCache(CACHE_NAME);
        logger.info("Node2Cache started");

        node3 = createManager();
        Cache<String, Object> node3Cache = node3.getCache(CACHE_NAME);
        logger.info("Node3Cache started");

        // Put some items on node1
        writeItems(node1Cache);

        // Get all items on node2. This will save them to L1 cache on node2
        readItems(node2Cache);

        // See the great performance with L1 enabled as everything read from L1 cache and there are no remote calls at all
        //readItems(node2Cache);

        // Write and see worse performance with L1 enabled as every write needs to invalidate L1 cache on node2 too
        //writeItems(node1Cache);

        // Kill node3
        node3.stop();

        // Wait
        logger.infof("Stopped node3. Will wait %d milliseconds", TIME_BEFORE_RESTORE_NODE);
        Thread.sleep(TIME_BEFORE_RESTORE_NODE);

        // Start node3 again
        logger.info("Going to start node3 again");

        node3 = createManager();
        node3Cache = node3.getCache(CACHE_NAME);
        logger.info("Node3Cache started again");

        logger.info("Test finished successfuly");
    } finally {
        if (node1 != null) node1.stop();
        if (node2 != null) node2.stop();
        if (node3 != null) node3.stop();
    }
}
 
Example 9
Source File: DistributedCacheConcurrentWritesTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static BasicCache<String, SessionEntityWrapper<UserSessionEntity>> createCache(String nodeName) {
    EmbeddedCacheManager mgr = createManager(nodeName);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = mgr.getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
    return cache;
}
 
Example 10
Source File: InfinispanSessionCacheIdMapperUpdater.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static SessionIdMapperUpdater addTokenStoreUpdaters(Context context, SessionIdMapper mapper, SessionIdMapperUpdater previousIdMapperUpdater) {
    ServletContext servletContext = context.getServletContext();
    String containerName = servletContext == null ? null : servletContext.getInitParameter(AdapterConstants.REPLICATION_CONFIG_CONTAINER_PARAM_NAME);
    String cacheName = servletContext == null ? null : servletContext.getInitParameter(AdapterConstants.REPLICATION_CONFIG_SSO_CACHE_PARAM_NAME);

    // the following is based on https://github.com/jbossas/jboss-as/blob/7.2.0.Final/clustering/web-infinispan/src/main/java/org/jboss/as/clustering/web/infinispan/DistributedCacheManagerFactory.java#L116-L122
    String host = context.getParent() == null ? "" : context.getParent().getName();
    String contextPath = context.getPath();
    if ("/".equals(contextPath)) {
        contextPath = "/ROOT";
    }
    String deploymentSessionCacheName = host + contextPath;

    if (containerName == null || cacheName == null || deploymentSessionCacheName == null) {
        LOG.warnv("Cannot determine parameters of SSO cache for deployment {0}.", host + contextPath);

        return previousIdMapperUpdater;
    }

    String cacheContainerLookup = DEFAULT_CACHE_CONTAINER_JNDI_NAME + "/" + containerName;

    try {
        EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) new InitialContext().lookup(cacheContainerLookup);

        Configuration ssoCacheConfiguration = cacheManager.getCacheConfiguration(cacheName);
        if (ssoCacheConfiguration == null) {
            Configuration cacheConfiguration = cacheManager.getCacheConfiguration(deploymentSessionCacheName);
            if (cacheConfiguration == null) {
                LOG.debugv("Using default configuration for SSO cache {0}.{1}.", containerName, cacheName);
                ssoCacheConfiguration = cacheManager.getDefaultCacheConfiguration();
            } else {
                LOG.debugv("Using distributed HTTP session cache configuration for SSO cache {0}.{1}, configuration taken from cache {2}",
                  containerName, cacheName, deploymentSessionCacheName);
                ssoCacheConfiguration = cacheConfiguration;
                cacheManager.defineConfiguration(cacheName, ssoCacheConfiguration);
            }
        } else {
            LOG.debugv("Using custom configuration of SSO cache {0}.{1}.", containerName, cacheName);
        }

        CacheMode ssoCacheMode = ssoCacheConfiguration.clustering().cacheMode();
        if (ssoCacheMode != CacheMode.REPL_ASYNC && ssoCacheMode != CacheMode.REPL_SYNC) {
            LOG.warnv("SSO cache mode is {0}, it is recommended to use replicated mode instead.", ssoCacheConfiguration.clustering().cacheModeString());
        }

        Cache<String, String[]> ssoCache = cacheManager.getCache(cacheName, true);
        final SsoSessionCacheListener listener = new SsoSessionCacheListener(ssoCache, mapper);
        ssoCache.addListener(listener);

        // Not possible to add listener for cross-DC support because of too old Infinispan in AS 7
        warnIfRemoteStoreIsUsed(ssoCache);

        LOG.debugv("Added distributed SSO session cache, lookup={0}, cache name={1}", cacheContainerLookup, cacheName);

        SsoCacheSessionIdMapperUpdater updater = new SsoCacheSessionIdMapperUpdater(ssoCache, previousIdMapperUpdater);

        return updater;
    } catch (NamingException ex) {
        LOG.warnv("Failed to obtain distributed session cache container, lookup={0}", cacheContainerLookup);
        return previousIdMapperUpdater;
    }
}
 
Example 11
Source File: InfinispanSessionCacheIdMapperUpdater.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static SessionIdMapperUpdater addTokenStoreUpdaters(DeploymentInfo deploymentInfo, SessionIdMapper mapper, SessionIdMapperUpdater previousIdMapperUpdater) {
    Map<String, String> initParameters = deploymentInfo.getInitParameters();
    String containerName = initParameters == null ? null : initParameters.get(AdapterConstants.REPLICATION_CONFIG_CONTAINER_PARAM_NAME);
    String cacheName = initParameters == null ? null : initParameters.get(AdapterConstants.REPLICATION_CONFIG_SSO_CACHE_PARAM_NAME);

    if (containerName == null || cacheName == null) {
        LOG.warnv("Cannot determine parameters of SSO cache for deployment {0}.", deploymentInfo.getDeploymentName());

        return previousIdMapperUpdater;
    }

    String cacheContainerLookup = DEFAULT_CACHE_CONTAINER_JNDI_NAME + "/" + containerName;
    String deploymentSessionCacheName = deploymentInfo.getDeploymentName();

    try {
        EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) new InitialContext().lookup(cacheContainerLookup);

        Configuration ssoCacheConfiguration = cacheManager.getCacheConfiguration(cacheName);
        if (ssoCacheConfiguration == null) {
            Configuration cacheConfiguration = cacheManager.getCacheConfiguration(deploymentSessionCacheName);
            if (cacheConfiguration == null) {
                LOG.debugv("Using default configuration for SSO cache {0}.{1}.", containerName, cacheName);
                ssoCacheConfiguration = cacheManager.getDefaultCacheConfiguration();
            } else {
                LOG.debugv("Using distributed HTTP session cache configuration for SSO cache {0}.{1}, configuration taken from cache {2}",
                  containerName, cacheName, deploymentSessionCacheName);
                ssoCacheConfiguration = cacheConfiguration;
                cacheManager.defineConfiguration(cacheName, ssoCacheConfiguration);
            }
        } else {
            LOG.debugv("Using custom configuration of SSO cache {0}.{1}.", containerName, cacheName);
        }

        CacheMode ssoCacheMode = ssoCacheConfiguration.clustering().cacheMode();
        if (ssoCacheMode != CacheMode.REPL_ASYNC && ssoCacheMode != CacheMode.REPL_SYNC) {
            LOG.warnv("SSO cache mode is {0}, it is recommended to use replicated mode instead.", ssoCacheConfiguration.clustering().cacheModeString());
        }

        Cache<String, String[]> ssoCache = cacheManager.getCache(cacheName, true);
        final SsoSessionCacheListener listener = new SsoSessionCacheListener(ssoCache, mapper);
        ssoCache.addListener(listener);

        addSsoCacheCrossDcListener(ssoCache, listener);

        LOG.debugv("Added distributed SSO session cache, lookup={0}, cache name={1}", cacheContainerLookup, cacheName);

        LOG.debugv("Adding session listener for SSO session cache, lookup={0}, cache name={1}", cacheContainerLookup, cacheName);
        SsoCacheSessionIdMapperUpdater updater = new SsoCacheSessionIdMapperUpdater(ssoCache, previousIdMapperUpdater);
        deploymentInfo.addSessionListener(updater);

        return updater;
    } catch (NamingException ex) {
        LOG.warnv("Failed to obtain distributed session cache container, lookup={0}", cacheContainerLookup);
        return previousIdMapperUpdater;
    }
}
 
Example 12
Source File: InfinispanSessionCacheIdMapperUpdater.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static SessionIdMapperUpdater addTokenStoreUpdaters(ServletContext servletContext, SessionIdMapper mapper, SessionIdMapperUpdater previousIdMapperUpdater) {
    String containerName = servletContext.getInitParameter(AdapterConstants.REPLICATION_CONFIG_CONTAINER_PARAM_NAME);
    String cacheName = servletContext.getInitParameter(AdapterConstants.REPLICATION_CONFIG_SSO_CACHE_PARAM_NAME);

    // the following is based on https://github.com/jbossas/jboss-as/blob/7.2.0.Final/clustering/web-infinispan/src/main/java/org/jboss/as/clustering/web/infinispan/DistributedCacheManagerFactory.java#L116-L122
    String contextPath = servletContext.getContextPath();
    if (contextPath == null || contextPath.isEmpty() || "/".equals(contextPath)) {
        contextPath = "/ROOT";
    }
    String deploymentSessionCacheName = contextPath;

    if (containerName == null || cacheName == null) {
        LOG.warnv("Cannot determine parameters of SSO cache for deployment {0}.", contextPath);

        return previousIdMapperUpdater;
    }

    String cacheContainerLookup = DEFAULT_CACHE_CONTAINER_JNDI_NAME + "/" + containerName;

    try {
        EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) new InitialContext().lookup(cacheContainerLookup);

        Configuration ssoCacheConfiguration = cacheManager.getCacheConfiguration(cacheName);
        if (ssoCacheConfiguration == null) {
            Configuration cacheConfiguration = cacheManager.getCacheConfiguration(deploymentSessionCacheName);
            if (cacheConfiguration == null) {
                LOG.debugv("Using default configuration for SSO cache {0}.{1}.", containerName, cacheName);
                ssoCacheConfiguration = cacheManager.getDefaultCacheConfiguration();
            } else {
                LOG.debugv("Using distributed HTTP session cache configuration for SSO cache {0}.{1}, configuration taken from cache {2}",
                  containerName, cacheName, deploymentSessionCacheName);
                ssoCacheConfiguration = cacheConfiguration;
                cacheManager.defineConfiguration(cacheName, ssoCacheConfiguration);
            }
        } else {
            LOG.debugv("Using custom configuration of SSO cache {0}.{1}.", containerName, cacheName);
        }

        CacheMode ssoCacheMode = ssoCacheConfiguration.clustering().cacheMode();
        if (ssoCacheMode != CacheMode.REPL_ASYNC && ssoCacheMode != CacheMode.REPL_SYNC) {
            LOG.warnv("SSO cache mode is {0}, it is recommended to use replicated mode instead.", ssoCacheConfiguration.clustering().cacheModeString());
        }

        Cache<String, String[]> ssoCache = cacheManager.getCache(cacheName, true);
        final SsoSessionCacheListener listener = new SsoSessionCacheListener(ssoCache, mapper);
        ssoCache.addListener(listener);

        addSsoCacheCrossDcListener(ssoCache, listener);

        LOG.debugv("Added distributed SSO session cache, lookup={0}, cache name={1}", cacheContainerLookup, cacheName);

        SsoCacheSessionIdMapperUpdater updater = new SsoCacheSessionIdMapperUpdater(ssoCache, previousIdMapperUpdater) {
            @Override
            public void close() throws Exception {
                ssoCache.stop();
            }
        };

        return updater;
    } catch (NamingException ex) {
        LOG.warnv("Failed to obtain distributed session cache container, lookup={0}", cacheContainerLookup);
        return previousIdMapperUpdater;
    }
}
 
Example 13
Source File: InfinispanSessionDataStorage.java    From pippo with Apache License 2.0 2 votes vote down vote up
/**
 * Manage session with the cache specified and CacheManager specified.
 *
 * @param cacheManager cache manager
 * @param cacheName cache name
 */
public InfinispanSessionDataStorage(EmbeddedCacheManager cacheManager, String cacheName) {
    this.sessions = cacheManager.getCache(cacheName);
}