org.infinispan.manager.DefaultCacheManager Java Examples

The following examples show how to use org.infinispan.manager.DefaultCacheManager. 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: InfinispanListen.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Construct a simple local cache manager with default configuration
   DefaultCacheManager cacheManager = new DefaultCacheManager();
   // Define local cache configuration
   cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
   // Obtain the local cache
   Cache<String, String> cache = cacheManager.getCache("local");
   // Register a listener
   cache.addListener(new MyListener());
   // Store some values
   cache.put("key1", "value1");
   cache.put("key2", "value2");
   cache.put("key1", "newValue");
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example #2
Source File: InfinispanLibrayImpl.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 초기화
 * @param configFile
 * @param cacheName
 * @param loginCacheName
 * @throws IOException
 */
@Override
public void initialize(String configFile, String cacheName, String loginCacheName)
        throws IOException {
    try {
        StringUtils.isNotNull("configFile", configFile);

        cacheManager = new DefaultCacheManager(configFile);

        this.cacheName = cacheName;
        this.loginCacheName = loginCacheName;

        cache = cacheManager.getCache(cacheName);
        loginCache = cacheManager.getCache(loginCacheName);

        waitForConnectionReady();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #3
Source File: Infinispan10Driver.java    From hazelcast-simulator with Apache License 2.0 6 votes vote down vote up
@Override
public void startVendorInstance() throws Exception {
    String workerType = get("WORKER_TYPE");
    if ("javaclient".equals(workerType)) {
         Properties hotrodProperties = new Properties();
        hotrodProperties.setProperty("infinispan.client.hotrod.server_list", get("server_list"));
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().withProperties(hotrodProperties);
        Configuration configuration = configurationBuilder.build();
        RemoteCacheManager remoteCacheManager = new RemoteCacheManager(configuration);
        this.cacheContainer = remoteCacheManager;
    } else {
        DefaultCacheManager defaultCacheManager = new DefaultCacheManager("infinispan.xml");
        this.cacheContainer = defaultCacheManager;
        HotRodServerConfiguration hotRodServerConfiguration = new HotRodServerConfigurationBuilder()
                .host(get("PRIVATE_ADDRESS")).port(11222).build();
        this.hotRodServer = new HotRodServer();
        hotRodServer.start(hotRodServerConfiguration, defaultCacheManager);
    }
}
 
Example #4
Source File: Infinispan9Driver.java    From hazelcast-simulator with Apache License 2.0 6 votes vote down vote up
@Override
public void startVendorInstance() throws Exception {
    String workerType = get("WORKER_TYPE");
    if ("javaclient".equals(workerType)) {
        Properties hotrodProperties = new Properties();
        hotrodProperties.setProperty("infinispan.client.hotrod.server_list", get("server_list"));
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().withProperties(hotrodProperties);
        Configuration configuration = configurationBuilder.build();
        RemoteCacheManager remoteCacheManager = new RemoteCacheManager(configuration);
        this.cacheContainer = remoteCacheManager;
    } else {
        DefaultCacheManager defaultCacheManager = new DefaultCacheManager("infinispan.xml");
        this.cacheContainer = defaultCacheManager;
        HotRodServerConfiguration hotRodServerConfiguration = new HotRodServerConfigurationBuilder()
                .host(get("PRIVATE_ADDRESS")).port(11222).build();
        this.hotRodServer = new HotRodServer();
        hotRodServer.start(hotRodServerConfiguration, defaultCacheManager);
    }
}
 
Example #5
Source File: InfinispanTest.java    From bucket4j with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() throws MalformedURLException, URISyntaxException {
    cacheManager1 = new DefaultCacheManager(getGlobalConfiguration());
    cacheManager1.defineConfiguration("my-cache",
            new ConfigurationBuilder()
                    .clustering()
                    .cacheMode(CacheMode.DIST_SYNC)
                    .hash().numOwners(2)
                    .build()
    );

    cache = cacheManager1.getCache("my-cache");
    readWriteMap = toMap(cache);

    cacheManager2 = new DefaultCacheManager(getGlobalConfiguration());
    cacheManager2.defineConfiguration("my-cache",
            new ConfigurationBuilder()
                    .clustering()
                    .cacheMode(CacheMode.DIST_SYNC)
                    .hash().numOwners(2)
                    .build()
    );
    cacheManager2.getCache("my-cache");
}
 
Example #6
Source File: InfinispanEmbeddedCacheConfig.java    From spring4-sandbox with Apache License 2.0 6 votes vote down vote up
@Override
@Bean
public CacheManager cacheManager() {

	return new SpringEmbeddedCacheManager(
			new DefaultCacheManager(
				new ConfigurationBuilder()
					.eviction()
						.maxEntries(20000)
						.strategy(EvictionStrategy.LIRS)
					.expiration()
						.wakeUpInterval(5000L)
						.maxIdle(120000L)
		           .build()
				)
			);
}
 
Example #7
Source File: InfinispanDistributed.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   // Setup up a clustered cache manager
   GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
   // Initialize the cache manager
   DefaultCacheManager cacheManager = new DefaultCacheManager(global.build());
   //Create cache configuration
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.clustering().cacheMode(CacheMode.DIST_SYNC);
   // Obtain a cache
   Cache<String, String> cache = cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
         .getOrCreateCache("cache", builder.build());

   // Store the current node address in some random keys
   for (int i = 0; i < 10; i++) {
      cache.put(UUID.randomUUID().toString(), cacheManager.getNodeAddress());
   }
   // Display the current cache contents for the whole cluster
   cache.entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Display the current cache contents for this node
   cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).entrySet()
         .forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example #8
Source File: ConcurrencyLockingTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected DefaultCacheManager getVersionedCacheManager() {
    GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();


    boolean allowDuplicateJMXDomains = true;

    gcb.globalJmxStatistics().allowDuplicateDomains(allowDuplicateJMXDomains);

    final DefaultCacheManager cacheManager = new DefaultCacheManager(gcb.build());
    ConfigurationBuilder invalidationConfigBuilder = new ConfigurationBuilder();
    Configuration invalidationCacheConfiguration = invalidationConfigBuilder.build();
    cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_CACHE_NAME, invalidationCacheConfiguration);

    ConfigurationBuilder counterConfigBuilder = new ConfigurationBuilder();
    counterConfigBuilder.invocationBatching().enable();
    counterConfigBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
    counterConfigBuilder.transaction().lockingMode(LockingMode.PESSIMISTIC);
    Configuration counterCacheConfiguration = counterConfigBuilder.build();

    cacheManager.defineConfiguration("COUNTER_CACHE", counterCacheConfiguration);
    return cacheManager;
}
 
Example #9
Source File: InfinispanReplicated.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   // Setup up a clustered cache manager
   GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
   // Initialize the cache manager
   DefaultCacheManager cacheManager = new DefaultCacheManager(global.build());
   // Create a replicated synchronous configuration
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.clustering().cacheMode(CacheMode.REPL_SYNC);
   Configuration cacheConfig = builder.build();
   // Create a cache
   Cache<String, String> cache = cacheManager.administration()
           .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
           .getOrCreateCache("cache", cacheConfig);

   // Store the current node address in some random keys
   for(int i=0; i < 10; i++) {
      cache.put(UUID.randomUUID().toString(), cacheManager.getNodeAddress());
   }
   // Display the current cache contents for the whole cluster
   cache.entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Display the current cache contents for this node
   cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP)
      .entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example #10
Source File: CachingModule.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
private EmbeddedCacheManager provideEmbeddedCacheManager(@Named("mongodb.hosts") String hosts,
                                                         @Named("mongodb.port") Integer port,
                                                         @Named("mongodb.source") String source,
                                                         @Named("mongodb.database") String database,
                                                         @Named("mongodb.username") String username,
                                                         @Named("mongodb.password") String password) {

    var builder = new ParserRegistry().parse(cacheConfig);
    var configurationBuilder = builder.getNamedConfigurationBuilders().get("differ.ackAwaitingCommands");

    configurationBuilder.persistence().
            addStore(MongoDBStoreConfigurationBuilder.class).
            connectionURI(createConnectionString(hosts, port, database, username, password, source)).
            collection("infinispan_cachestore_ackAwaitingCommands");

    return new DefaultCacheManager(builder, true);
}
 
Example #11
Source File: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that if remove executes before put, then put still succeeds.
 *
 * @throws Exception
 */
@Test
public void testGetRemovePutOnNonExisting() throws Exception {
    final DefaultCacheManager cacheManager = getVersionedCacheManager();
    ExecutorService executor = Executors.newSingleThreadExecutor();

    RemoveThread removeThread = new RemoveThread(cacheManager);

    Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
    cache.remove("key");
    startBatch(cache);
    cache.get("key");
    executor.execute(removeThread);
    removeThread.getLatch().await();
    cache.putForExternalRead("key", "value1");
    endBatch(cache);
    Assert.assertEquals(cache.get("key"), "value1");
    Assert.assertTrue(removeThread.isSuccess());
}
 
Example #12
Source File: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
     * Test that if a put of an existing key is removed after the put and before tx commit, it is evicted
     *
     * @throws Exception
     */
    @Test
    public void testGetRemovePutEternalOnExisting() throws Exception {
        final DefaultCacheManager cacheManager = getVersionedCacheManager();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        RemoveThread removeThread = new RemoveThread(cacheManager);

        Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
        cache.put("key", "value0");
        startBatch(cache);
        cache.get("key");
        executor.execute(removeThread);
        cache.putForExternalRead("key", "value1");
        removeThread.getLatch().await();
        try {
            endBatch(cache);
//            Assert.fail("Write skew should be detected");
        } catch (Exception e) {

        }
        Assert.assertNull(cache.get("key"));
        Assert.assertTrue(removeThread.isSuccess());
    }
 
Example #13
Source File: InfinispanEmbeddedProducer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Singleton
@Produces
EmbeddedCacheManager manager() {
    if (config.xmlConfig.isPresent()) {
        String configurationFile = config.xmlConfig.get();
        try {
            InputStream configurationStream = FileLookupFactory.newInstance().lookupFileStrict(configurationFile,
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilderHolder configHolder = new ParserRegistry().parse(configurationStream, null);
            verifyTransactionConfiguration(configHolder.getDefaultConfigurationBuilder(), "default");
            for (Map.Entry<String, ConfigurationBuilder> entry : configHolder.getNamedConfigurationBuilders().entrySet()) {
                verifyTransactionConfiguration(entry.getValue(), entry.getKey());
            }
            return new DefaultCacheManager(configHolder, true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return new DefaultCacheManager();
}
 
Example #14
Source File: InfinispanKeyStorageProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Cache<String, PublicKeysEntry> getKeysCache() {
    GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();
    gcb.globalJmxStatistics().allowDuplicateDomains(true).enabled(true);

    final DefaultCacheManager cacheManager = new DefaultCacheManager(gcb.build());

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.memory()
            .evictionStrategy(EvictionStrategy.REMOVE)
            .evictionType(EvictionType.COUNT)
            .size(InfinispanConnectionProvider.KEYS_CACHE_DEFAULT_MAX);
    cb.jmxStatistics().enabled(true);
    Configuration cfg = cb.build();

    cacheManager.defineConfiguration(InfinispanConnectionProvider.KEYS_CACHE_NAME, cfg);
    return cacheManager.getCache(InfinispanConnectionProvider.KEYS_CACHE_NAME);
}
 
Example #15
Source File: TestCacheManagerFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
<T extends StoreConfigurationBuilder<?, T> & RemoteStoreConfigurationChildBuilder<T>> EmbeddedCacheManager createManager(int threadId, String cacheName, Class<T> builderClass) {
    System.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperty("jgroups.tcp.port", "53715");
    GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();

    boolean clustered = false;
    boolean async = false;
    boolean allowDuplicateJMXDomains = true;

    if (clustered) {
        gcb = gcb.clusteredDefault();
        gcb.transport().clusterName("test-clustering");
    }

    gcb.globalJmxStatistics().allowDuplicateDomains(allowDuplicateJMXDomains);

    EmbeddedCacheManager cacheManager = new DefaultCacheManager(gcb.build());

    Configuration invalidationCacheConfiguration = getCacheBackedByRemoteStore(threadId, cacheName, builderClass);

    cacheManager.defineConfiguration(cacheName, invalidationCacheConfiguration);
    cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
    return cacheManager;

}
 
Example #16
Source File: ClusterTest.java    From hacep with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusterSize() {
    System.setProperty("grid.buffer", "10");

    RulesConfigurationTestImpl rulesConfigurationTest = RulesTestBuilder.buildV1();
    RulesManager rulesManager = new RulesManager(rulesConfigurationTest);
    rulesManager.start(null, null, null);

    LOGGER.info("Start test cluster size");
    Cache<Key, HAKieSession> cache1 = startNodes(2, rulesManager).getCache();
    Cache<Key, HAKieSession> cache2 = startNodes(2, rulesManager).getCache();

    assertEquals(2, ((DefaultCacheManager) cache1.getCacheManager()).getClusterSize());
    assertEquals(2, ((DefaultCacheManager) cache2.getCacheManager()).getClusterSize());
    LOGGER.info("End test cluster size");
    rulesManager.stop();
}
 
Example #17
Source File: InfinispanConfiguration.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
@ApplicationScoped
@Produces
public EmbeddedCacheManager cacheManager(
        @RegistryProperties("registry.infinispan.transport") Properties properties
) {
    GlobalConfigurationBuilder gConf = GlobalConfigurationBuilder.defaultClusteredBuilder();

    gConf.serialization()
            .marshaller(new JavaSerializationMarshaller())
            .whiteList()
            .addRegexps(
                    "io.apicurio.registry.storage.",
                    TupleId.class.getName(),
                    MapValue.class.getName()
            );

    TransportConfigurationBuilder tConf = gConf.transport();
    tConf.clusterName(clusterName);
    if (properties.size() > 0) {
        tConf.withProperties(properties);
    }

    return new DefaultCacheManager(gConf.build(), true);
}
 
Example #18
Source File: L1SerializationIssueTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private EmbeddedCacheManager createManager() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperty("jgroups.tcp.port", "53715");
    GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();

    gcb = gcb.clusteredDefault();
    gcb.transport().clusterName("test-clustering");

    gcb.globalJmxStatistics().allowDuplicateDomains(true);

    EmbeddedCacheManager cacheManager = new DefaultCacheManager(gcb.build());


    ConfigurationBuilder distConfigBuilder = new ConfigurationBuilder();
    ClusteringConfigurationBuilder clusterConfBuilder = distConfigBuilder.clustering();
    clusterConfBuilder.cacheMode(CacheMode.DIST_SYNC);
    clusterConfBuilder.hash().numOwners(NUM_OWNERS);
    clusterConfBuilder.l1().enabled(L1_ENABLED)
            .lifespan(L1_LIFESPAN_MS)
            .cleanupTaskFrequency(L1_CLEANER_MS);

    Configuration distCacheConfiguration = distConfigBuilder.build();

    cacheManager.defineConfiguration(CACHE_NAME, distCacheConfiguration);
    return cacheManager;
}
 
Example #19
Source File: InfinispanStreams.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Construct a simple local cache manager with default configuration
   DefaultCacheManager cacheManager = new DefaultCacheManager();
   // Define local cache configuration
   cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
   // Obtain the local cache
   Cache<String, String> cache = cacheManager.getCache("local");
   // Store some values
   int range = 10;
   IntStream.range(0, range).boxed().forEach(i -> cache.put(i + "-key", i + "-value"));
   // Map and reduce the keys
   int result = cache.keySet().stream()
         .map(e -> Integer.valueOf(e.substring(0, e.indexOf("-"))))
         .collect(() -> Collectors.summingInt(i -> i.intValue()));
   System.out.printf("Result = %d\n", result);
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example #20
Source File: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
    public void testPutExternalRemoveOnExisting() throws Exception {
        final DefaultCacheManager cacheManager = getVersionedCacheManager();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        RemoveThread removeThread = new RemoveThread(cacheManager);

        Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
        cache.put("key", "value0");
        startBatch(cache);
        cache.putForExternalRead("key", "value1");
        executor.execute(removeThread);
        removeThread.getLatch().await();
        try {
            endBatch(cache);
//            Assert.fail("Write skew should be detected");
        } catch (Exception e) {

        }
        Assert.assertNull(cache.get("key"));
        Assert.assertTrue(removeThread.isSuccess());
    }
 
Example #21
Source File: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Test that if a put of an existing key is removed after the put and before tx commit, it is evicted
 *
 * @throws Exception
 */
@Test
public void testGetRemovePutOnExisting() throws Exception {
    final DefaultCacheManager cacheManager = getVersionedCacheManager();
    ExecutorService executor = Executors.newSingleThreadExecutor();

    RemoveThread removeThread = new RemoveThread(cacheManager);

    Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
    cache.put("key", "value0");
    startBatch(cache);
    cache.get("key");
    executor.execute(removeThread);
    removeThread.getLatch().await();
    cache.put("key", "value1");
    try {
        endBatch(cache);
        Assert.fail("Write skew should be detected");
    } catch (Exception e) {


    }
    Assert.assertNull(cache.get("key"));
    Assert.assertTrue(removeThread.isSuccess());
}
 
Example #22
Source File: ClusterManager.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private ClusterManagerImpl(File confDir, String jgroupsConfigurationFile,
        Map<String, String> jgroupsProperties) {
    GlobalConfiguration configuration = new GlobalConfigurationBuilder()
            .transport()
            .defaultTransport()
            .addProperty("configurationFile",
                    getConfigurationFilePropertyValue(confDir, jgroupsConfigurationFile))
            .globalJmxStatistics()
            .enable()
            .build();
    cacheManager = doWithSystemProperties(jgroupsProperties,
            () -> new DefaultCacheManager(configuration));
    executor = MoreExecutors2.newCachedThreadPool("Cluster-Manager-Worker");
}
 
Example #23
Source File: ClusteredCacheBehaviorTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public EmbeddedCacheManager createManager() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperty("jgroups.tcp.port", "53715");
    GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();

    boolean clustered = true;
    boolean async = false;
    boolean allowDuplicateJMXDomains = true;

    if (clustered) {
        gcb = gcb.clusteredDefault();
        gcb.transport().clusterName("test-clustering");
    }
    gcb.globalJmxStatistics().allowDuplicateDomains(allowDuplicateJMXDomains);

    EmbeddedCacheManager cacheManager = new DefaultCacheManager(gcb.build());


    ConfigurationBuilder invalidationConfigBuilder = new ConfigurationBuilder();
    if (clustered) {
        invalidationConfigBuilder.clustering().cacheMode(async ? CacheMode.INVALIDATION_ASYNC : CacheMode.INVALIDATION_SYNC);
    }
    Configuration invalidationCacheConfiguration = invalidationConfigBuilder.build();

    cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_CACHE_NAME, invalidationCacheConfiguration);
    return cacheManager;

}
 
Example #24
Source File: InfinispanMultimap.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
   // Construct a local cache manager with default configuration
   DefaultCacheManager cacheManager = new DefaultCacheManager();

   // Obtain a multimap cache manager from the regular cache manager
   MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cacheManager);

   // Define de multimap cache configuration, as a regular cache
   multimapCacheManager.defineConfiguration("multimap", new ConfigurationBuilder().build());

   // Get the MultimapCache
   MultimapCache<String, String> multimap = multimapCacheManager.get("multimap");

   // Store multiple values in a key
   CompletableFuture.allOf(
         multimap.put("key", "value1"),
         multimap.put("key", "value2"),
         multimap.put("key", "value3"))
         .whenComplete((nil, ex) -> {
            // Retrieve the values
            multimap.get("key").whenComplete((values, ex2) -> {
               // Print them out
               System.out.println(values);
               // Stop the cache manager and release all resources
               cacheManager.stop();
            });
         });
}
 
Example #25
Source File: QuarkusCacheManagerProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public <C> C getCacheManager(Config.Scope config) {
    try {
        InputStream configurationStream = loadConfiguration(config);
        ConfigurationBuilderHolder builder = new ParserRegistry().parse(configurationStream);

        if (builder.getNamedConfigurationBuilders().get("sessions").clustering().cacheMode().isClustered()) {
            configureTransportStack(config, builder);
        }

        return (C) new DefaultCacheManager(builder, false);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: DistributedCacheConcurrentWritesTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static EmbeddedCacheManager createManager(String nodeName) {
    System.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperty("jgroups.tcp.port", "53715");
    GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();

    boolean clustered = true;
    boolean async = false;
    boolean allowDuplicateJMXDomains = true;

    if (clustered) {
        gcb = gcb.clusteredDefault();
        gcb.transport().clusterName("test-clustering");
        gcb.transport().nodeName(nodeName);
    }
    gcb.globalJmxStatistics().allowDuplicateDomains(allowDuplicateJMXDomains);

    EmbeddedCacheManager cacheManager = new DefaultCacheManager(gcb.build());


    ConfigurationBuilder distConfigBuilder = new ConfigurationBuilder();
    if (clustered) {
        distConfigBuilder.clustering().cacheMode(async ? CacheMode.DIST_ASYNC : CacheMode.DIST_SYNC);
        distConfigBuilder.clustering().hash().numOwners(1);

        // Disable L1 cache
        distConfigBuilder.clustering().hash().l1().enabled(false);
    }
    Configuration distConfig = distConfigBuilder.build();

    cacheManager.defineConfiguration(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, distConfig);
    return cacheManager;

}
 
Example #27
Source File: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected DefaultCacheManager getVersionedCacheManager() {
    GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();


    boolean clustered = false;
    boolean async = false;
    boolean allowDuplicateJMXDomains = true;

    if (clustered) {
        gcb.transport().defaultTransport();
    }
    gcb.globalJmxStatistics().allowDuplicateDomains(allowDuplicateJMXDomains);

    final DefaultCacheManager cacheManager = new DefaultCacheManager(gcb.build());
    ConfigurationBuilder invalidationConfigBuilder = new ConfigurationBuilder();
    invalidationConfigBuilder
            //.invocationBatching().enable()
            .transaction().transactionMode(TransactionMode.TRANSACTIONAL)
            .transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
            .locking().isolationLevel(IsolationLevel.REPEATABLE_READ).writeSkewCheck(true).versioning().enable().scheme(VersioningScheme.SIMPLE);


    //invalidationConfigBuilder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ).writeSkewCheck(true).versioning().enable().scheme(VersioningScheme.SIMPLE);

    if (clustered) {
        invalidationConfigBuilder.clustering().cacheMode(async ? CacheMode.INVALIDATION_ASYNC : CacheMode.INVALIDATION_SYNC);
    }
    Configuration invalidationCacheConfiguration = invalidationConfigBuilder.build();
    cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_CACHE_NAME, invalidationCacheConfiguration);
    return cacheManager;
}
 
Example #28
Source File: OutdatedTopologyExceptionReproducerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private EmbeddedCacheManager createManager() {
        System.setProperty("java.net.preferIPv4Stack", "true");
        System.setProperty("jgroups.tcp.port", "53715");
        GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();

        boolean clustered = true;
        boolean async = false;
        boolean allowDuplicateJMXDomains = true;

        if (clustered) {
            gcb = gcb.clusteredDefault();
            gcb.transport().clusterName("test-clustering");
        }

        gcb.globalJmxStatistics().allowDuplicateDomains(allowDuplicateJMXDomains);

        EmbeddedCacheManager cacheManager = new DefaultCacheManager(gcb.build());


        ConfigurationBuilder invalidationConfigBuilder = new ConfigurationBuilder();
        if (clustered) {
            invalidationConfigBuilder.clustering().cacheMode(async ? CacheMode.INVALIDATION_ASYNC : CacheMode.INVALIDATION_SYNC);
        }

        // Uncomment this to have test fixed!!!
//        invalidationConfigBuilder.customInterceptors()
//                .addInterceptor()
//                .before(NonTransactionalLockingInterceptor.class)
//                .interceptorClass(StateTransferInterceptor.class);

        Configuration invalidationCacheConfiguration = invalidationConfigBuilder.build();

        cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_CACHE_NAME, invalidationCacheConfiguration);
        return cacheManager;

    }
 
Example #29
Source File: WeatherApp.java    From infinispan-embedded-tutorial with Apache License 2.0 5 votes vote down vote up
public WeatherApp() throws InterruptedException, IOException {
   cacheManager = new DefaultCacheManager(WeatherApp.class.getResourceAsStream("/weatherapp-infinispan.xml"));
   listener = new ClusterListener(2);
   cacheManager.addListener(listener);
   cache = cacheManager.getCache("weather");
   cache.addListener(new CacheListener());
   weatherService = initWeatherService(cache);

   System.out.println("---- Waiting for cluster to form ----");
   listener.clusterFormedLatch.await();
}
 
Example #30
Source File: InfinispanFactory.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Create cache manager with custom config file.
 *
 * @param file config file
 * @return cache manager
 */
public static EmbeddedCacheManager create(String file) {
    try {
        return new DefaultCacheManager(file);
    } catch (IOException ex) {
        log.error("", ex);
        throw new PippoRuntimeException(ex);
    }
}