org.infinispan.client.hotrod.RemoteCache Java Examples

The following examples show how to use org.infinispan.client.hotrod.RemoteCache. 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: ConcurrencyJDGRemoveSessionTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static Thread createWorker(Cache<String, SessionEntityWrapper<UserSessionEntity>> cache, int threadId) {
    System.out.println("Retrieved cache: " + threadId);

    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);

    if (threadId == 1) {
        remoteCache1 = remoteCache;
    } else {
        remoteCache2 = remoteCache;
    }

    AtomicInteger counter = threadId ==1 ? successfulListenerWrites : successfulListenerWrites2;
    HotRodListener listener = new HotRodListener(cache, remoteCache, counter);
    remoteCache.addClientListener(listener);

    return new RemoteCacheWorker(remoteCache, threadId);
    //return new CacheWorker(cache, threadId);
}
 
Example #2
Source File: ConcurrencyJDGCacheReplaceTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static Thread createWorker(Cache<String, SessionEntityWrapper<UserSessionEntity>> cache, int threadId) {
    System.out.println("Retrieved cache: " + threadId);

    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);

    if (threadId == 1) {
        remoteCache1 = remoteCache;
    } else {
        remoteCache2 = remoteCache;
    }

    AtomicInteger counter = threadId ==1 ? successfulListenerWrites : successfulListenerWrites2;
    HotRodListener listener = new HotRodListener(cache, remoteCache, counter);
    remoteCache.addClientListener(listener);

    return new RemoteCacheWorker(remoteCache, threadId);
    //return new CacheWorker(cache, threadId);
}
 
Example #3
Source File: HotrodCache.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Future<Boolean> remove(final K key, final V value) {
    Objects.requireNonNull(key);
    Objects.requireNonNull(value);

    return withCache(cache -> {
        final RemoteCache<K, V> remoteCache = (RemoteCache<K, V>) cache;
        return remoteCache.getWithMetadataAsync(key).thenCompose(metadataValue -> {
            if (metadataValue != null && value.equals(metadataValue.getValue())) {
                // If removeWithVersionAsync() returns false here (meaning that the value was updated in between),
                // the updated value shall prevail and no new removal attempt with a new getWithMetadataAsync() invocation will be done.
                return remoteCache.removeWithVersionAsync(key, metadataValue.getVersion());
            } else {
                return CompletableFuture.completedFuture(Boolean.FALSE);
            }
        });
    });
}
 
Example #4
Source File: InfinispanServerTasks.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   // Upload the task using the REST API
   uploadTask();

   // Get a cache to execute the task
   final RemoteCache<String, String> execCache = getExecCache();

   // Create task parameters
   Map<String, String> parameters = new HashMap<>();
   parameters.put("greetee", "developer");

   // Execute hello task
   String greet = execCache.execute("hello-task", parameters);
   System.out.printf("Greeting = %s\n", greet);

   // Stop the cache manager and release all resources
   execCache.getRemoteCacheManager().stop();
}
 
Example #5
Source File: InfinispanScripting.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Create a configuration for a locally-running server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
   // Connect to the server
   RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
   // Retrieve the cache containing the scripts
   RemoteCache<String, String> scriptCache = cacheManager.getCache("___script_cache");
   // Create a simple script which multiplies to numbers
   scriptCache.put("simple.js", "multiplicand * multiplier");
   // Obtain the remote cache
   RemoteCache<String, Integer> cache = cacheManager.administration().getOrCreateCache("test", DefaultTemplate.DIST_SYNC);
   // Create the parameters for script execution
   Map<String, Object> params = new HashMap<>();
   params.put("multiplicand", 10);
   params.put("multiplier", 20);
   // Run the script on the server, passing in the parameters
   Object result = cache.execute("simple.js", params);
   // Print the result
   System.out.printf("Result = %s\n", result);
   // Stop the cache manager and release resources
   cacheManager.stop();
}
 
Example #6
Source File: InfinispanRemoteQuery.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private static void addPersonSchema(RemoteCacheManager cacheManager) throws IOException {
   // Get the serialization context of the client
   SerializationContext ctx = MarshallerUtil.getSerializationContext(cacheManager);

   // Use ProtoSchemaBuilder to define a Protobuf schema on the client
   ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder();
   String fileName = "person.proto";
   String protoFile = protoSchemaBuilder
         .fileName(fileName)
         .addClass(Person.class)
         .packageName("tutorial")
         .build(ctx);

   // Retrieve metadata cache
   RemoteCache<String, String> metadataCache =
         cacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME);

   // Define the new schema on the server too
   metadataCache.put(fileName, protoFile);
}
 
Example #7
Source File: InfinispanRemoteContinuousQuery.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private static void addInstapostsSchema(RemoteCacheManager cacheManager) throws IOException {
   // Get the serialization context of the client
   SerializationContext ctx = MarshallerUtil.getSerializationContext(cacheManager);

   // Use ProtoSchemaBuilder to define a Protobuf schema on the client
   ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder();
   String fileName = "instapost.proto";
   String protoFile = protoSchemaBuilder
         .fileName(fileName)
         .addClass(InstaPost.class)
         .packageName("tutorial")
         .build(ctx);

   // Retrieve metadata cache
   RemoteCache<String, String> metadataCache =
         cacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME);

   // Define the new schema on the server too
   metadataCache.putIfAbsent(fileName, protoFile);
}
 
Example #8
Source File: InfinispanRemote.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Create a configuration for a locally-running server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer()
            .host("127.0.0.1")
            .port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
          .security().authentication()
            //Add user credentials.
            .username("username")
            .password("password")
            .realm("default")
            .saslMechanism("DIGEST-MD5");
   // Connect to the server
   RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
   // Create test cache, if such does not exist
   cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache("test", DefaultTemplate.DIST_SYNC);
   // Obtain the remote cache
   RemoteCache<String, String> cache = cacheManager.getCache("test");
   /// 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: InfinispanNearCache.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Create a client configuration connecting to a local server
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
   builder.nearCache().mode(NearCacheMode.INVALIDATED).maxEntries(20).cacheNamePattern("near-.*");

   // Connect to the server
   RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());

   // Create one remote cache with near caching disabled and one with near caching enabled
   RemoteCache<Integer, String> numbers = cacheManager.administration().getOrCreateCache("numbers", DefaultTemplate.DIST_SYNC);
   RemoteCache<Integer, String> nearNumbers = cacheManager.administration().getOrCreateCache("near-numbers", DefaultTemplate.DIST_SYNC);

   for (int i = 1; i<= 20; i++) {
      numbers.put(i, String.valueOf(i));
      nearNumbers.put(i, String.valueOf(i));
   }

   // Read both caches data
   readCache(numbers);
   readCache(nearNumbers);

   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example #10
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void test() {

        RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11322;192.168.0.58:11422", true);
        RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION");

        Set<Object> keySet = cache.keySet();

        Iterator<Object> i = keySet.iterator();
        System.out.println("============= KHAN_SESSION");
        while (i.hasNext()) {
            Object key = i.next();
            System.out.println("> key=" + key);
            Object value = cache.get(key);
            System.out.println("> value=" + value);
            System.out.println("");
        }
        System.out.println("=============");
    }
 
Example #11
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void test2() {
    RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11322;192.168.0.58:11422", true);
    RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION_LOGIN");

    Set<Object> keySet = cache.keySet();

    Iterator<Object> i = keySet.iterator();
    System.out.println("============= KHAN_SESSION_LOGIN");
    while (i.hasNext()) {
        Object key = i.next();
        System.out.println("> key=" + key);
        Object value = cache.get(key);
        System.out.println("> value=" + value);
        System.out.println("");
    }
    System.out.println("=============");
}
 
Example #12
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testRemoteLoginCache() {
    RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11422;192.168.0.58:11322", true);
    RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION_LOGIN_REMOTE");

    Set<Object> keySet = cache.keySet();

    Iterator<Object> i = keySet.iterator();
    System.out.println("============= KHAN_SESSION_LOGIN_REMOTE");
    while (i.hasNext()) {
        Object key = i.next();
        System.out.println("> key=" + key);
        Object value = cache.get(key);
        System.out.println("> value=" + value);
        System.out.println("");
    }
    System.out.println("=============");
}
 
Example #13
Source File: TestCacheResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/remote-cache-last-session-refresh/{user-session-id}")
@Produces(MediaType.APPLICATION_JSON)
public int getRemoteCacheLastSessionRefresh(@PathParam("user-session-id") String userSessionId) {
    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);
    if (remoteCache == null) {
        return -1;
    } else {
        SessionEntityWrapper<UserSessionEntity> userSession = (SessionEntityWrapper<UserSessionEntity>) remoteCache.get(userSessionId);
        if (userSession == null) {
            return -1;
        } else {
            return userSession.getEntity().getLastSessionRefresh();
        }
    }
}
 
Example #14
Source File: RemoteCacheSessionListener.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static <K, V extends SessionEntity> RemoteCacheSessionListener createListener(KeycloakSession session, Cache<K, SessionEntityWrapper<V>> cache, RemoteCache<K, SessionEntityWrapper<V>> remoteCache) {
    /*boolean isCoordinator = InfinispanUtil.isCoordinator(cache);

    // Just cluster coordinator will fetch userSessions from remote cache.
    // In case that coordinator is failover during state fetch, there is slight risk that not all userSessions will be fetched to local cluster. Assume acceptable for now
    RemoteCacheSessionListener listener;
    if (isCoordinator) {
        logger.infof("Will fetch initial state from remote cache for cache '%s'", cache.getName());
        listener = new FetchInitialStateCacheListener();
    } else {
        logger.infof("Won't fetch initial state from remote cache for cache '%s'", cache.getName());
        listener = new DontFetchInitialStateCacheListener();
    }*/

    RemoteCacheSessionListener<K, V> listener = new RemoteCacheSessionListener<>();
    listener.init(session, cache, remoteCache);

    return listener;
}
 
Example #15
Source File: RemoteCacheSessionsLoader.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected int getIspnSegmentsCount(RemoteCache remoteCache) {
    OperationsFactory operationsFactory = ((RemoteCacheImpl) remoteCache).getOperationsFactory();

    // Same like RemoteCloseableIterator.startInternal
    IterationStartOperation iterationStartOperation = operationsFactory.newIterationStartOperation(null, null, null, sessionsPerSegment, false, null);
    IterationStartResponse startResponse = await(iterationStartOperation.execute());

    try {
        // Could happen for non-clustered caches
        if (startResponse.getSegmentConsistentHash() == null) {
            return -1;
        } else {
            return startResponse.getSegmentConsistentHash().getNumSegments();
        }
    } finally {
        startResponse.getChannel().close();
    }
}
 
Example #16
Source File: InfinispanCodeToTokenStoreProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void lazyInit(KeycloakSession session) {
    if (codeCache == null) {
        synchronized (this) {
            if (codeCache == null) {
                InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
                Cache cache = connections.getCache(InfinispanConnectionProvider.ACTION_TOKEN_CACHE);

                RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);

                if (remoteCache != null) {
                    LOG.debugf("Having remote stores. Using remote cache '%s' for single-use cache of code", remoteCache.getName());
                    this.codeCache = () -> {
                        // Doing this way as flag is per invocation
                        return remoteCache.withFlags(Flag.FORCE_RETURN_VALUE);
                    };
                } else {
                    LOG.debugf("Not having remote stores. Using normal cache '%s' for single-use cache of code", cache.getName());
                    this.codeCache = () -> {
                        return cache;
                    };
                }
            }
        }
    }
}
 
Example #17
Source File: InfinispanUserSessionProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private <K, V extends SessionEntity> boolean checkRemoteCache(KeycloakSession session, Cache<K, SessionEntityWrapper<V>> ispnCache, RemoteCacheInvoker.MaxIdleTimeLoader maxIdleLoader) {
    Set<RemoteStore> remoteStores = InfinispanUtil.getRemoteStores(ispnCache);

    if (remoteStores.isEmpty()) {
        log.debugf("No remote store configured for cache '%s'", ispnCache.getName());
        return false;
    } else {
        log.infof("Remote store configured for cache '%s'", ispnCache.getName());

        RemoteCache<K, SessionEntityWrapper<V>> remoteCache = (RemoteCache) remoteStores.iterator().next().getRemoteCache();

        if (remoteCache == null) {
            throw new IllegalStateException("No remote cache available for the infinispan cache: " + ispnCache.getName());
        }

        remoteCacheInvoker.addRemoteCache(ispnCache.getName(), remoteCache, maxIdleLoader);

        RemoteCacheSessionListener hotrodListener = RemoteCacheSessionListener.createListener(session, ispnCache, remoteCache);
        remoteCache.addClientListener(hotrodListener);
        return true;
    }
}
 
Example #18
Source File: InfinispanSingleUseTokenStoreProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void lazyInit(KeycloakSession session) {
    if (tokenCache == null) {
        synchronized (this) {
            if (tokenCache == null) {
                InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
                Cache cache = connections.getCache(InfinispanConnectionProvider.ACTION_TOKEN_CACHE);

                RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);

                if (remoteCache != null) {
                    LOG.debugf("Having remote stores. Using remote cache '%s' for single-use cache of token", remoteCache.getName());
                    this.tokenCache = () -> {
                        // Doing this way as flag is per invocation
                        return remoteCache.withFlags(Flag.FORCE_RETURN_VALUE);
                    };
                } else {
                    LOG.debugf("Not having remote stores. Using normal cache '%s' for single-use cache of token", cache.getName());
                    this.tokenCache = () -> {
                        return cache;
                    };
                }
            }
        }
    }
}
 
Example #19
Source File: RemoteCaches.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testRemoteCache() {
    RemoteCacheManager cacheManager = new RemoteCacheManager("192.168.0.58:11422;192.168.0.58:11322", true);
    RemoteCache<Object, Object> cache = cacheManager.getCache("KHAN_SESSION_REMOTE");

    Set<Object> keySet = cache.keySet();

    Iterator<Object> i = keySet.iterator();
    System.out.println("============= KHAN_SESSION_REMOTE");
    while (i.hasNext()) {
        Object key = i.next();
        System.out.println("> key=" + key);
        Object value = cache.get(key);
        System.out.println("> value=" + value);
        System.out.println("");
    }
    System.out.println("=============");
}
 
Example #20
Source File: CrossDCAwareCacheFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
static CrossDCAwareCacheFactory getFactory(Cache<String, Serializable> workCache, Set<RemoteStore> remoteStores) {
    if (remoteStores.isEmpty()) {
        logger.debugf("No configured remoteStore available. Cross-DC scenario is not used");
        return new InfinispanCacheWrapperFactory(workCache);
    } else {
        logger.debugf("RemoteStore is available. Cross-DC scenario will be used");

        if (remoteStores.size() > 1) {
            logger.warnf("More remoteStores configured for work cache. Will use just the first one");
        }

        // For cross-DC scenario, we need to return underlying remoteCache for atomic operations to work properly
        RemoteStore remoteStore = remoteStores.iterator().next();
        RemoteCache remoteCache = remoteStore.getRemoteCache();

        if (remoteCache == null) {
            String cacheName = remoteStore.getConfiguration().remoteCacheName();
            throw new IllegalStateException("Remote cache '" + cacheName + "' is not available.");
        }

        return new RemoteCacheWrapperFactory(remoteCache);
    }
}
 
Example #21
Source File: HotRodSearchClient.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
private void registerProto(boolean reset, String... protoKeys) {
    RemoteCache<Object, Object> cache = manager.getCache(PROTO_CACHE);
    if (cache == null) {
        throw new IllegalStateException(String.format("Missing %s cache!", PROTO_CACHE));
    }

    SerializationContext ctx = MarshallerUtil.getSerializationContext(manager);
    FileDescriptorSource fds = new FileDescriptorSource();
    for (String protoKey : protoKeys) {
        if (reset || !cache.containsKey(protoKey)) {
            String protoContent = IoUtil.toString(getClass().getResourceAsStream("/" + protoKey));
            log.info(String.format("Using proto schema: %s%n%s", protoKey, protoContent));
            fds.addProtoFile(protoKey, protoContent);
            cache.put(protoKey, protoContent);
        }
    }
    ctx.registerProtoFiles(fds);
    ctx.registerMarshaller(new ArtifactTypeMarshaller());
    ctx.registerMarshaller(new ArtifactMarshaller());
}
 
Example #22
Source File: RemoteCacheSessionsLoader.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public RemoteCacheSessionsLoaderContext computeLoaderContext(KeycloakSession session) {
    RemoteCache remoteCache = getRemoteCache(session);
    int sessionsTotal = remoteCache.size();
    int ispnSegments = getIspnSegmentsCount(remoteCache);

    return new RemoteCacheSessionsLoaderContext(ispnSegments, sessionsPerSegment, sessionsTotal);

}
 
Example #23
Source File: BoardEventStarter.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void registerBoardListener() {
	InfinispanRemoteDatastoreProvider provider = (InfinispanRemoteDatastoreProvider) emf.unwrap( SessionFactoryImplementor.class )
			.getServiceRegistry().getService( DatastoreProvider.class );

	RemoteCache<Object, Object> board = provider.getCache( "Board" );
	board.addClientListener( boardEventListener );
}
 
Example #24
Source File: HotrodCacheTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void verifyRemoveWithValue(final BasicCache<Object, Object> cache, final String key,
        final Object value, final boolean expectedRemoveOperationResult) {
    final org.infinispan.client.hotrod.RemoteCache<Object, Object> remoteCache = (RemoteCache<Object, Object>) cache;
    verify(remoteCache).getWithMetadataAsync(key);
    if (expectedRemoveOperationResult) {
        verify(remoteCache).removeWithVersionAsync(eq(key), anyLong());
    }
}
 
Example #25
Source File: RemoteInfinispanCacheMeterBinderProvider.java    From infinispan-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public MeterBinder getMeterBinder(Cache cache, Iterable<Tag> tags) {

   if (cache.getNativeCache() instanceof RemoteCache) {
      return new RemoteInfinispanCacheMeterBinder((RemoteCache) cache.getNativeCache(), tags);
   } else {
      return new RemoteInfinispanCacheMeterBinder(null, tags);
   }
}
 
Example #26
Source File: RemoteCacheInvoker.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <K, V extends SessionEntity> void replace(TopologyInfo topology, RemoteCache<K, SessionEntityWrapper<V>> remoteCache, long lifespanMs, long maxIdleMs, K key, SessionUpdateTask<V> task) {
    boolean replaced = false;
    int replaceIteration = 0;
    while (!replaced && replaceIteration < InfinispanUtil.MAXIMUM_REPLACE_RETRIES) {
        replaceIteration++;

        VersionedValue<SessionEntityWrapper<V>> versioned = remoteCache.getWithMetadata(key);
        if (versioned == null) {
            logger.warnf("Not found entity to replace for key '%s'", key);
            return;
        }

        SessionEntityWrapper<V> sessionWrapper = versioned.getValue();
        final V session = sessionWrapper.getEntity();

        // Run task on the remote session
        task.runUpdate(session);

        if (logger.isTraceEnabled()) {
            logger.tracef("%s: Before replaceWithVersion. Entity to write version %d: %s", logTopologyData(topology, replaceIteration),
                    versioned.getVersion(), session);
        }

        replaced = remoteCache.replaceWithVersion(key, SessionEntityWrapper.forTransport(session), versioned.getVersion(), lifespanMs, TimeUnit.MILLISECONDS, maxIdleMs, TimeUnit.MILLISECONDS);

        if (!replaced) {
            logger.debugf("%s: Failed to replace entity '%s' version %d. Will retry again", logTopologyData(topology, replaceIteration), key, versioned.getVersion());
        } else {
            if (logger.isTraceEnabled()) {
                logger.tracef("%s: Replaced entity version %d in remote cache: %s", logTopologyData(topology, replaceIteration), versioned.getVersion(), session);
            }
        }
    }

    if (!replaced) {
        logger.warnf("Failed to replace entity '%s' in remote cache '%s'", key, remoteCache.getName());
    }
}
 
Example #27
Source File: InfinispanNearCache.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
private static void readCache(RemoteCache<Integer, String> cache) {
   Instant start = Instant.now();
   Random random = new Random();
   random.ints(10_000, 1, 20).forEach(num -> cache.get(num));
   Instant finish = Instant.now();
   long timeElapsed = Duration.between(start, finish).toMillis();
   System.out.println(String.format("Time to complete with cache %s is %d milliseconds", cache.getName(), timeElapsed));
}
 
Example #28
Source File: InfinispanRemoteContinuousQuery.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
private static void addRandomPost(RemoteCache<String, InstaPost> cache) {
   String id = UUID.randomUUID().toString();
   Random random = new Random();
   // Create the random post
   InstaPost post = new InstaPost(id, USERS.get(random.nextInt(USERS.size())), HASHTAGS.get(random.nextInt(HASHTAGS.size())));
   // Put a post in the cache
   cache.put(id, post);
}
 
Example #29
Source File: InfinispanUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static RemoteCache getRemoteCache(Cache ispnCache) {
    Set<RemoteStore> remoteStores = getRemoteStores(ispnCache);
    if (remoteStores.isEmpty()) {
        return null;
    } else {
        return remoteStores.iterator().next().getRemoteCache();
    }
}
 
Example #30
Source File: RemoteCacheInvoker.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <K, V extends SessionEntity> void runOnRemoteCache(TopologyInfo topology, RemoteCache<K, SessionEntityWrapper<V>> remoteCache, long maxIdleMs, K key, SessionUpdateTask<V> task, SessionEntityWrapper<V> sessionWrapper) {
    final V session = sessionWrapper.getEntity();
    SessionUpdateTask.CacheOperation operation = task.getOperation(session);

    switch (operation) {
        case REMOVE:
            remoteCache.remove(key);
            break;
        case ADD:
            remoteCache.put(key, sessionWrapper.forTransport(), task.getLifespanMs(), TimeUnit.MILLISECONDS, maxIdleMs, TimeUnit.MILLISECONDS);
            break;
        case ADD_IF_ABSENT:
            SessionEntityWrapper<V> existing = remoteCache
                    .withFlags(Flag.FORCE_RETURN_VALUE)
                    .putIfAbsent(key, sessionWrapper.forTransport(), -1, TimeUnit.MILLISECONDS, maxIdleMs, TimeUnit.MILLISECONDS);
            if (existing != null) {
                logger.debugf("Existing entity in remote cache for key: %s . Will update it", key);

                replace(topology, remoteCache, task.getLifespanMs(), maxIdleMs, key, task);
            }
            break;
        case REPLACE:
            replace(topology, remoteCache, task.getLifespanMs(), maxIdleMs, key, task);
            break;
        default:
            throw new IllegalStateException("Unsupported state " +  operation);
    }
}