org.infinispan.manager.EmbeddedCacheManager Java Examples

The following examples show how to use org.infinispan.manager.EmbeddedCacheManager. 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: OnlineStudentSchedulingContainer.java    From unitime with Apache License 2.0 6 votes vote down vote up
public OnlineSectioningServerContext getServerContext(final Long academicSessionId) {
	return new OnlineSectioningServerContext() {
		@Override
		public Long getAcademicSessionId() {
			return academicSessionId;
		}

		@Override
		public boolean isWaitTillStarted() {
			return false;
		}

		@Override
		public EmbeddedCacheManager getCacheManager() {
			return null;
		}

		@Override
		public LockService getLockService() {
			return null;
		}
	};
}
 
Example #2
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 #3
Source File: RegisterMarshallersTask.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@Override
public Object call() throws Exception {
	EmbeddedCacheManager cacheManager = ctx.getCache().get().getCacheManager();
	ProtobufMetadataManager protobufMetadataManager = cacheManager.getGlobalComponentRegistry().getComponent( ProtobufMetadataManager.class );

	protobufMetadataManager.registerMarshaller( new Board.Marshaller() );
	protobufMetadataManager.registerMarshaller( new BoardId.Marshaller() );
	protobufMetadataManager.registerMarshaller( new BoardMessage.Marshaller() );
	protobufMetadataManager.registerMarshaller( new BoardMessageId.Marshaller() );
	protobufMetadataManager.registerMarshaller( new Message.Marshaller() );
	protobufMetadataManager.registerMarshaller( new MessageId.Marshaller() );
	protobufMetadataManager.registerMarshaller( new MessageTag.Marshaller() );
	protobufMetadataManager.registerMarshaller( new MessageTagId.Marshaller() );
	protobufMetadataManager.registerMarshaller( new Tag.Marshaller() );
	protobufMetadataManager.registerMarshaller( new TagId.Marshaller() );

	return ANY_NOTNULL_NUMBER;
}
 
Example #4
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 #5
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 #6
Source File: InfinispanServerExtension.java    From infinispan-spring-boot with Apache License 2.0 6 votes vote down vote up
public void start() {
   if (hotRodServer == null) {
      TestResourceTracker.setThreadTestName("InfinispanServer");
      ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
      EmbeddedCacheManager ecm = TestCacheManagerFactory.createCacheManager(
            new GlobalConfigurationBuilder().nonClusteredDefault().defaultCacheName("default"),
            configurationBuilder);

      for (String cacheName : initialCaches) {
         ecm.createCache(cacheName, new ConfigurationBuilder().build());
      }
      HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder();
      serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler());
      hotRodServer = HotRodTestingUtil.startHotRodServer(ecm, host, port, serverBuilder);
   }
}
 
Example #7
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 #8
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 #9
Source File: AbstractServer.java    From unitime with Apache License 2.0 6 votes vote down vote up
@Override
public void releaseMasterLockIfHeld() {
	if (iMasterThread != null) {
		iMasterThread.release();
	} else if (Boolean.TRUE.equals(getProperty("ReloadIsNeeded", Boolean.FALSE))) {
		iLog.info("Reloading server...");
		final Long sessionId = getAcademicSession().getUniqueId();
		loadOnMaster(new OnlineSectioningServerContext() {
			@Override
			public Long getAcademicSessionId() { return sessionId; }
			@Override
			public boolean isWaitTillStarted() { return false; }
			@Override
			public EmbeddedCacheManager getCacheManager() { return null; }
			@Override
			public LockService getLockService() { return null; }
		});
	}
}
 
Example #10
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 #11
Source File: InfinispanHealthIndicator.java    From keycloak-health-checks with Apache License 2.0 5 votes vote down vote up
private EmbeddedCacheManager lookupCacheManager() {
    try {
        return (EmbeddedCacheManager) new InitialContext().lookup(KEYCLOAK_CACHE_MANAGER_JNDI_NAME);
    } catch (NamingException e) {
        log.warnv("Could not find EmbeddedCacheManager with name: {0}", KEYCLOAK_CACHE_MANAGER_JNDI_NAME);
        throw new RuntimeException(e);
    }
}
 
Example #12
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 #13
Source File: InfinispanFactory.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Create cache manager with custom idle time.
 *
 * @param idleTime idle time in seconds
 * @return cache manager
 */
public static EmbeddedCacheManager create(long idleTime) {
    Configuration configuration = new ConfigurationBuilder()
            .expiration().maxIdle(idleTime, TimeUnit.SECONDS)
            .build();
    return new DefaultCacheManager(configuration);
}
 
Example #14
Source File: CacheManagerCustomizerTestSupport.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
public static EmbeddedCacheManager newEmbeddedCacheManagerInstance() {
    return new DefaultCacheManager(
        new org.infinispan.configuration.global.GlobalConfigurationBuilder()
            .build(),
        new org.infinispan.configuration.cache.ConfigurationBuilder()
            .build(),
        false
    );
}
 
Example #15
Source File: MovieDBHelper.java    From popular-movie-store with Apache License 2.0 5 votes vote down vote up
@Autowired
public MovieDBHelper(RestTemplate restTemplate, MovieStoreProps movieStoreProps,
                     EmbeddedCacheManager cacheManager) {
    this.restTemplate = restTemplate;
    this.movieStoreProps = movieStoreProps;
    this.moviesCache = cacheManager
        .getCache(POPULAR_MOVIES_CACHE).getAdvancedCache();
}
 
Example #16
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 #17
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 #18
Source File: DefaultInfinispanConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void initContainerManaged(EmbeddedCacheManager cacheManager) {
    this.cacheManager = cacheManager;
    containerManaged = true;

    long realmRevisionsMaxEntries = this.cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME).getCacheConfiguration().memory().size();
    realmRevisionsMaxEntries = realmRevisionsMaxEntries > 0
            ? 2 * realmRevisionsMaxEntries
            : InfinispanConnectionProvider.REALM_REVISIONS_CACHE_DEFAULT_MAX;

    this.cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_REVISIONS_CACHE_NAME, getRevisionCacheConfig(realmRevisionsMaxEntries));
    this.cacheManager.getCache(InfinispanConnectionProvider.REALM_REVISIONS_CACHE_NAME, true);

    long userRevisionsMaxEntries = this.cacheManager.getCache(InfinispanConnectionProvider.USER_CACHE_NAME).getCacheConfiguration().memory().size();
    userRevisionsMaxEntries = userRevisionsMaxEntries > 0
            ? 2 * userRevisionsMaxEntries
            : InfinispanConnectionProvider.USER_REVISIONS_CACHE_DEFAULT_MAX;

    this.cacheManager.defineConfiguration(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME, getRevisionCacheConfig(userRevisionsMaxEntries));
    this.cacheManager.getCache(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME, true);
    this.cacheManager.getCache(InfinispanConnectionProvider.AUTHORIZATION_CACHE_NAME, true);
    this.cacheManager.getCache(InfinispanConnectionProvider.AUTHENTICATION_SESSIONS_CACHE_NAME, true);
    this.cacheManager.getCache(InfinispanConnectionProvider.KEYS_CACHE_NAME, true);
    this.cacheManager.getCache(InfinispanConnectionProvider.ACTION_TOKEN_CACHE, true);

    long authzRevisionsMaxEntries = this.cacheManager.getCache(InfinispanConnectionProvider.AUTHORIZATION_CACHE_NAME).getCacheConfiguration().memory().size();
    authzRevisionsMaxEntries = authzRevisionsMaxEntries > 0
            ? 2 * authzRevisionsMaxEntries
            : InfinispanConnectionProvider.AUTHORIZATION_REVISIONS_CACHE_DEFAULT_MAX;

    this.cacheManager.defineConfiguration(InfinispanConnectionProvider.AUTHORIZATION_REVISIONS_CACHE_NAME, getRevisionCacheConfig(authzRevisionsMaxEntries));
    this.cacheManager.getCache(InfinispanConnectionProvider.AUTHORIZATION_REVISIONS_CACHE_NAME, true);

    this.topologyInfo = new TopologyInfo(this.cacheManager, config, false);

    logger.debugv("Using container managed Infinispan cache container, lookup={0}", cacheManager);
}
 
Example #19
Source File: InfinispanServerTestResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {
    TestResourceTracker.setThreadTestName("InfinispanServer");
    EmbeddedCacheManager ecm = TestCacheManagerFactory.createCacheManager(
            new GlobalConfigurationBuilder().nonClusteredDefault().defaultCacheName("default"),
            new ConfigurationBuilder());
    ecm.defineConfiguration("magazine", new ConfigurationBuilder().build());
    // Client connects to a non default port
    hotRodServer = HotRodTestingUtil.startHotRodServer(ecm, 11232);
    return Collections.emptyMap();
}
 
Example #20
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 #21
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);
    }
}
 
Example #22
Source File: DefaultInfinispanConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void lazyInit() {
    if (cacheManager == null) {
        synchronized (this) {
            if (cacheManager == null) {
                EmbeddedCacheManager managedCacheManager = null;
                Iterator<ManagedCacheManagerProvider> providers = ServiceLoader.load(ManagedCacheManagerProvider.class, DefaultInfinispanConnectionProvider.class.getClassLoader())
                        .iterator();

                if (providers.hasNext()) {
                    ManagedCacheManagerProvider provider = providers.next();
                    
                    if (providers.hasNext()) {
                        throw new RuntimeException("Multiple " + org.keycloak.cluster.ManagedCacheManagerProvider.class + " providers found.");
                    }
                    
                    managedCacheManager = provider.getCacheManager(config);
                }
                
                if (managedCacheManager == null) {
                    if (!config.getBoolean("embedded", false)) {
                        throw new RuntimeException("No " + ManagedCacheManagerProvider.class.getName() + " found. If running in embedded mode set the [embedded] property to this provider.");
                    }
                    initEmbedded();
                } else {
                    initContainerManaged(managedCacheManager);
                }

                logger.infof(topologyInfo.toString());

                remoteCacheProvider = new RemoteCacheProvider(config, cacheManager);
            }
        }
    }
}
 
Example #23
Source File: SpringEmbeddedCacheManagerFactoryBean.java    From java-platform with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 */
@Override
public void afterPropertiesSet() throws Exception {
   logger.info("Initializing SpringEmbeddedCacheManager instance ...");

   final EmbeddedCacheManager nativeEmbeddedCacheManager = createBackingEmbeddedCacheManager();
   this.cacheManager = new SpringEmbeddedCacheManager(nativeEmbeddedCacheManager);

   logger.info("Successfully initialized SpringEmbeddedCacheManager instance ["
                     + this.cacheManager + "]");
}
 
Example #24
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 #25
Source File: MemoryCounter.java    From unitime with Apache License 2.0 5 votes vote down vote up
private boolean skipObject(Object obj) {
	if (obj instanceof String) {
		// this will not cause a memory leak since
		// unused interned Strings will be thrown away
		if (obj == ((String) obj).intern()) {
			return true;
		}
	}
	if (obj instanceof Marshaller || obj instanceof EmbeddedCacheManager || obj instanceof Thread || obj instanceof Log || obj instanceof Logger || obj instanceof SolverContainer) return true;
	return (obj == null) || iVisited.containsKey(obj);
}
 
Example #26
Source File: ClusterHealthCheckImpl.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Promise<Status> promise) {
  VertxInternal vertxInternal = (VertxInternal) vertx;
  InfinispanClusterManager clusterManager = (InfinispanClusterManager) vertxInternal.getClusterManager();
  EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) clusterManager.getCacheContainer();
  Health health = cacheManager.getHealth();
  HealthStatus healthStatus = health.getClusterHealth().getHealthStatus();
  Status status = new Status().setOk(healthStatus == HealthStatus.HEALTHY);
  if (detailed) {
    status.setData(convert(health));
  }
  promise.complete(status);
}
 
Example #27
Source File: Lifecycle.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
public static void closeClustered(List<Vertx> clustered) throws Exception {
  for (Vertx vertx : clustered) {
    VertxInternal vertxInternal = (VertxInternal) vertx;

    InfinispanClusterManager clusterManager = getInfinispanClusterManager(vertxInternal.getClusterManager());

    ComponentStatus status = null;
    if (clusterManager != null) {
      EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) clusterManager.getCacheContainer();
      status = cacheManager.getStatus();

      Health health = cacheManager.getHealth();

      SECONDS.sleep(2); // Make sure rebalancing has been triggered

      long start = System.currentTimeMillis();
      try {
        while (health.getClusterHealth().getHealthStatus() != HealthStatus.HEALTHY
          && System.currentTimeMillis() - start < MILLISECONDS.convert(2, MINUTES)) {
          MILLISECONDS.sleep(100);
        }
      } catch (Exception ignore) {
      }
    }

    if (status == null || status.compareTo(STOPPING) >= 0) {
      vertxInternal.close();
    } else {
      CountDownLatch latch = new CountDownLatch(1);
      vertxInternal.close(ar -> {
        if (ar.failed()) {
          log.error("Failed to shutdown vert.x", ar.cause());
        }
        latch.countDown();
      });
      latch.await(2, TimeUnit.MINUTES);
    }
  }
}
 
Example #28
Source File: SpringCaching.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    // Create a cache programmatically for the example. There is no default cache
    EmbeddedCacheManager cacheManager = applicationContext.getBean(SpringEmbeddedCacheManager.class).getNativeCacheManager();
    cacheManager.administration()
          .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
          .getOrCreateCache("default", new ConfigurationBuilder().build());

    CachedObject cachePlayground = applicationContext.getBean(CachedObject.class);

    printWithTime(() -> cachePlayground.verySlowMethod());
    printWithTime(() -> cachePlayground.verySlowMethod());
}
 
Example #29
Source File: SpringAnnotationConfiguration.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
    // Create a cache programmatically for the example. There is no default cache
    EmbeddedCacheManager cacheManager = applicationContext.getBean(SpringEmbeddedCacheManager.class).getNativeCacheManager();
    cacheManager.administration()
          .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
          .getOrCreateCache("default", new ConfigurationBuilder().build());

    CachePlayground cachePlayground = applicationContext.getBean(CachePlayground.class);

    cachePlayground.add("Infinispan", "Is cool!");
    System.out.println(cachePlayground.getContent("Infinispan"));
}
 
Example #30
Source File: DistributedCacheWriteSkewTest.java    From keycloak with Apache License 2.0 4 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);

        //distConfigBuilder.storeAsBinary().enable().storeKeysAsBinary(false).storeValuesAsBinary(true);

        distConfigBuilder.versioning().enabled(true);
        distConfigBuilder.versioning().scheme(VersioningScheme.SIMPLE);

        distConfigBuilder.locking().writeSkewCheck(true);
        distConfigBuilder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
        distConfigBuilder.locking().concurrencyLevel(32);
        distConfigBuilder.locking().lockAcquisitionTimeout(1000, TimeUnit.SECONDS);

        distConfigBuilder.versioning().enabled(true);
        distConfigBuilder.versioning().scheme(VersioningScheme.SIMPLE);


       // distConfigBuilder.invocationBatching().enable();
        //distConfigBuilder.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
        distConfigBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
        distConfigBuilder.transaction().lockingMode(LockingMode.OPTIMISTIC);
    }
    Configuration distConfig = distConfigBuilder.build();

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

}