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

The following examples show how to use org.infinispan.manager.DefaultCacheManager#defineConfiguration() . 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: 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 5
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 6
Source File: Bucket4jInfinispanApplication.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 5 votes vote down vote up
@Bean
@Qualifier("RateLimit")
public ReadWriteMap<String, GridBucketState> map() {
    DefaultCacheManager cacheManager = new DefaultCacheManager();
    cacheManager.defineConfiguration("rateLimit", new ConfigurationBuilder().build());
    AdvancedCache<String, GridBucketState> cache = cacheManager.<String, GridBucketState>getCache("rateLimit").getAdvancedCache();
    FunctionalMapImpl<String, GridBucketState> functionalMap = FunctionalMapImpl.create(cache);
    return ReadWriteMapImpl.create(functionalMap);
}
 
Example 7
Source File: Bucket4jInfinispanRateLimiterTest.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
    DefaultCacheManager cacheManager = new DefaultCacheManager();
    cacheManager.defineConfiguration("rateLimit", new ConfigurationBuilder().build());
    AdvancedCache<String, GridBucketState> cache = cacheManager.<String, GridBucketState>getCache("rateLimit").getAdvancedCache();
    FunctionalMapImpl<String, GridBucketState> functionalMap = FunctionalMapImpl.create(cache);
    FunctionalMap.ReadWriteMap<String, GridBucketState> readWriteMap = ReadWriteMapImpl.create(functionalMap);
    target = new Bucket4jInfinispanRateLimiter(readWriteMap);
}
 
Example 8
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 9
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 10
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 11
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 12
Source File: InfinispanFunctional.java    From infinispan-simple-tutorials with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
   DefaultCacheManager cacheManager = new DefaultCacheManager();
   cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
   AdvancedCache<String, String> cache = cacheManager.<String, String>getCache("local").getAdvancedCache();
   FunctionalMapImpl<String, String> functionalMap = FunctionalMapImpl.create(cache);
   FunctionalMap.WriteOnlyMap<String, String> writeOnlyMap = WriteOnlyMapImpl.create(functionalMap);
   FunctionalMap.ReadOnlyMap<String, String> readOnlyMap = ReadOnlyMapImpl.create(functionalMap);

   // Execute two parallel write-only operation to store key/value pairs
   CompletableFuture<Void> writeFuture1 = writeOnlyMap.eval("key1", "value1",
      (v, writeView) -> writeView.set(v));
   CompletableFuture<Void> writeFuture2 = writeOnlyMap.eval("key2", "value2",
      (v, writeView) -> writeView.set(v));

   // When each write-only operation completes, execute a read-only operation to retrieve the value
   CompletableFuture<String> readFuture1 =
      writeFuture1.thenCompose(r -> readOnlyMap.eval("key1", EntryView.ReadEntryView::get));
   CompletableFuture<String> readFuture2 =
      writeFuture2.thenCompose(r -> readOnlyMap.eval("key2", EntryView.ReadEntryView::get));

   // When the read-only operation completes, print it out
   System.out.printf("Created entries: %n");
   CompletableFuture<Void> end = readFuture1.thenAcceptBoth(readFuture2, (v1, v2) ->
      System.out.printf("key1 = %s%nkey2 = %s%n", v1, v2));

   // Wait for this read/write combination to finish
   end.get();

   // Create a read-write map
   FunctionalMap.ReadWriteMap<String, String> readWriteMap = ReadWriteMapImpl.create(functionalMap);

   // Use read-write multi-key based operation to write new values
   // together with lifespan and return previous values
   Map<String, String> data = new HashMap<>();
   data.put("key1", "newValue1");
   data.put("key2", "newValue2");
   Traversable<String> previousValues = readWriteMap.evalMany(data, (v, readWriteView) -> {
      String prev = readWriteView.find().orElse(null);
      readWriteView.set(v, new MetaLifespan(Duration.ofHours(1).toMillis()));
      return prev;
   });

   // Use read-only multi-key operation to read current values for multiple keys
   Traversable<EntryView.ReadEntryView<String, String>> entryViews =
      readOnlyMap.evalMany(data.keySet(), readOnlyView -> readOnlyView);
   System.out.printf("Updated entries: %n");
   entryViews.forEach(view -> System.out.printf("%s%n", view));

   // Finally, print out the previous entry values
   System.out.printf("Previous entry values: %n");
   previousValues.forEach(prev -> System.out.printf("%s%n", prev));
}
 
Example 13
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();
}