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

The following examples show how to use org.infinispan.manager.DefaultCacheManager#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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
Source File: InfinispanMap.java    From infinispan-simple-tutorials with Apache License 2.0 5 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 a value
   cache.put("key", "value");
   // Retrieve the value and print it out
   System.out.printf("key = %s\n", cache.get("key"));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 11
Source File: InfinispanKubernetes.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws UnknownHostException {
   //Configure Infinispan to use default transport and Kubernetes configuration
   GlobalConfiguration globalConfig = new GlobalConfigurationBuilder().defaultCacheName("defaultCacheName")
  .transport()
         .defaultTransport()
         .addProperty("configurationFile", "default-configs/default-jgroups-kubernetes.xml")
         .build();


   // We need a distributed cache for the purpose of this demo
   Configuration cacheConfiguration = new ConfigurationBuilder()
         .clustering()
         .cacheMode(CacheMode.REPL_SYNC)
         .build();

   DefaultCacheManager cacheManager = new DefaultCacheManager(globalConfig, cacheConfiguration);
   cacheManager.defineConfiguration("default", cacheConfiguration);
   Cache<String, String> cache = cacheManager.getCache("default");

   //Each cluster member will update its own entry in the cache
   String hostname = Inet4Address.getLocalHost().getHostName();
   ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
   scheduler.scheduleAtFixedRate(() -> {
            String time = Instant.now().toString();
            cache.put(hostname, time);
            System.out.println("[" + time + "][" + hostname + "] Values from the cache: ");
            System.out.println(cache.entrySet());
         },
         0, 2, TimeUnit.SECONDS);

   try {
      //This container will operate for an hour and then it will die
      TimeUnit.HOURS.sleep(1);
   } catch (InterruptedException e) {
      scheduler.shutdown();
      cacheManager.stop();
   }
}
 
Example 12
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 13
Source File: CacheConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
private <K, V> Cache<K, V> buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) {

        cacheManager.defineConfiguration(cacheName, configuration);
        Cache<K, V> cache = cacheManager.getCache(cacheName);
        cache.addListener(listener);
        return cache;
    }
 
Example 14
Source File: InvalidationMode.java    From infinispan-simple-tutorials with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
   // Create a clustered configuration and a default cache named test
   GlobalConfiguration global = GlobalConfigurationBuilder.defaultClusteredBuilder().build();

   // Create the cache manager
   DefaultCacheManager cacheManager = new DefaultCacheManager(global);

   // Clustered mode invalidation sync. Can also be async
   Configuration config = new ConfigurationBuilder()
           .clustering().cacheMode(CacheMode.INVALIDATION_SYNC)
           .build();

   // Define a cache configuration
   cacheManager.defineConfiguration("test", config);

   // Retrieve the cache
   Cache<String, String> cache = cacheManager.getCache("test");

   Scanner scanner = new Scanner(System.in);
   String next = "";

   // Enter 'q' option to exit
   while (!next.equals("q")) {
      System.out.println(
            "Invalidation mode simple tutorial\n" +
                  "=================================\n" +
                  "`p` to put a key/value \n" +
                  "`pe` to put a key/value for external read \n" +
                  "`r` to remove a key \n" +
                  "`g` to get a key \n" +
                  "`q` to exit \n");
      System.out.println("Enter an option: ");
      next = scanner.next();

      switch (next) {
         case "p":
            putKeyValue(scanner, cache);
            break;
         case "pe":
            putForExternalReadKeyValue(scanner, cache);
            break;
         case "r":
            removeKey(scanner, cache);
            break;
         case "g":
            getKey(scanner, cache);
            break;

         default:
      }
   }

   // Goodbye!
   System.out.println("Good bye");

   // Stop the cache manager
   cacheManager.stop();
}