Java Code Examples for org.infinispan.Cache#put()
The following examples show how to use
org.infinispan.Cache#put() .
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: InfinispanDistributed.java From infinispan-simple-tutorials with Apache License 2.0 | 6 votes |
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 2
Source File: InfinispanListen.java From infinispan-simple-tutorials with Apache License 2.0 | 6 votes |
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: ConcurrencyVersioningTest.java From keycloak with Apache License 2.0 | 6 votes |
/** * 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 4
Source File: InfinispanReplicated.java From infinispan-simple-tutorials with Apache License 2.0 | 6 votes |
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 5
Source File: ConcurrencyVersioningTest.java From keycloak with Apache License 2.0 | 6 votes |
@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 6
Source File: TestServlet.java From quarkus with Apache License 2.0 | 5 votes |
@Transactional @Path("PUT/{cacheName}/{id}/{value}") @GET @Produces(MediaType.TEXT_PLAIN) public String put(@PathParam("cacheName") String cacheName, @PathParam("id") String id, @PathParam("value") String value, @QueryParam("shouldFail") String shouldFail) { log.info("Putting " + id + " with value: " + value + " into " + cacheName); Cache<byte[], byte[]> cache = emc.getCache(cacheName); byte[] result = cache.put(id.getBytes(StandardCharsets.UTF_8), value.getBytes(StandardCharsets.UTF_8)); if (Boolean.parseBoolean(shouldFail)) { throw new RuntimeException("Forced Exception!"); } return result == null ? "null" : new String(result, StandardCharsets.UTF_8); }
Example 7
Source File: ClusterTest.java From hacep with Apache License 2.0 | 5 votes |
@Test public void testEmptyHASession() { LOGGER.info("Start test empty HASessionID"); System.setProperty("grid.buffer", "10"); RulesConfigurationTestImpl rulesConfigurationTest = RulesTestBuilder.buildV1(); rulesConfigurationTest.registerChannel("additions", additionsChannel, replayChannel); RulesManager rulesManager = new RulesManager(rulesConfigurationTest); rulesManager.start(null, null, null); Cache<String, Object> cache1 = startNodes(2, rulesManager).getCache(); Cache<String, Object> cache2 = startNodes(2, rulesManager).getCache(); reset(replayChannel); String key = "1"; HAKieSession session1 = new HAKieSession(rulesManager, executorService); cache1.put(key, session1); HAKieSession serializedSessionCopy = (HAKieSession) cache2.get(key); Assert.assertNotNull(serializedSessionCopy); Assert.assertTrue(serializedSessionCopy.isSerialized()); reset(replayChannel, additionsChannel); HAKieSession session2 = ((HAKieSerializedSession) serializedSessionCopy).rebuild(); Assert.assertNotNull(session2); LOGGER.info("End test empty HASessionID"); rulesManager.stop(); }
Example 8
Source File: InfinispanMap.java From infinispan-simple-tutorials with Apache License 2.0 | 5 votes |
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: L1SerializationIssueTest.java From keycloak with Apache License 2.0 | 5 votes |
private void writeItems(Cache<String, Object> cache) { long start = System.currentTimeMillis(); for (int i=0 ; i < ITEMS_COUNT ; i++) { String key = "key-" + i; cache.put(key, new MySerializable()); } logger.infof("Write %d items in %d ms", ITEMS_COUNT, System.currentTimeMillis() - start); }
Example 10
Source File: InfinispanRemoteTest.java From thorntail with Apache License 2.0 | 5 votes |
@Test public void testBasic() throws Exception { //new CountDownLatch(1).await(); CacheContainer cacheContainer = (CacheContainer) new InitialContext().lookup("java:jboss/infinispan/container/server"); Cache<String,String> cache = cacheContainer.getCache("default"); cache.put("ham", "biscuit"); assertEquals("biscuit", cache.get("ham")); }
Example 11
Source File: HACEPImpl.java From hacep with Apache License 2.0 | 4 votes |
@Override public void suspend() { //this.router.suspend(); Cache<String, String> replicatedCache = dataGridManager.getReplicatedCache(); replicatedCache.put(Router.SUSPEND, String.valueOf(System.currentTimeMillis())); }
Example 12
Source File: ClusteredCacheBehaviorTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test public void testListener() throws Exception { EmbeddedCacheManager node1 = createManager(); EmbeddedCacheManager node2 = createManager(); Cache<String, Object> node1Cache = node1.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME); node1Cache.addListener(new CacheListener("node1")); Cache<String, Object> node2Cache = node2.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME); node2Cache.addListener(new CacheListener("node2")); System.out.println("node1 create entry"); node1Cache.put("key", "node1"); System.out.println("node1 create entry"); node1Cache.put("key", "node111"); System.out.println("node2 create entry"); node2Cache.put("key", "node2"); System.out.println("node1 remove entry"); node1Cache.remove("key"); System.out.println("node2 remove entry"); node2Cache.remove("key"); System.out.println("node2 put entry"); node2Cache.put("key", "node2"); System.out.println("node2 evict entry"); node2Cache.evict("key"); System.out.println("node1/node2 putExternal entry"); node1Cache.putForExternalRead("key", "common"); node2Cache.putForExternalRead("key", "common"); System.out.println("node2 remove entry"); node2Cache.remove("key"); System.out.println("node1 remove entry"); node1Cache.remove("key"); // test remove non-existing node 2, existing node 1 System.out.println("Test non existent remove"); System.out.println("node1 create entry"); node1Cache.put("key", "value"); System.out.println("node2 remove non-existent entry"); System.out.println("exists?: " + node2Cache.containsKey("key")); node2Cache.remove("key"); // test clear System.out.println("Test clear cache"); System.out.println("add key to node 1, key2 to node2"); node1Cache.putForExternalRead("key", "value"); node2Cache.putForExternalRead("key", "value"); node2Cache.putForExternalRead("key2", "value"); System.out.println("Clear from node1"); node1Cache.clear(); System.out.println("node 2 exists key2?: " + node2Cache.containsKey("key2")); System.out.println("node 2 exists key?: " + node2Cache.containsKey("key")); }
Example 13
Source File: DistributedCacheWriteSkewTest.java From keycloak with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { Cache<String, UserSessionEntity> cache1 = createManager("node1").getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME); Cache<String, UserSessionEntity> cache2 = createManager("node2").getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME); // Create initial item UserSessionEntity session = new UserSessionEntity(); session.setId("123"); session.setRealmId("foo"); session.setBrokerSessionId("!23123123"); session.setBrokerUserId(null); session.setUser("foo"); session.setLoginUsername("foo"); session.setIpAddress("123.44.143.178"); session.setStarted(Time.currentTime()); session.setLastSessionRefresh(Time.currentTime()); AuthenticatedClientSessionEntity clientSession = new AuthenticatedClientSessionEntity(UUID.randomUUID()); clientSession.setAuthMethod("saml"); clientSession.setAction("something"); clientSession.setTimestamp(1234); session.getAuthenticatedClientSessions().put(CLIENT_1_UUID.toString(), clientSession.getId()); cache1.put("123", session); //cache1.replace("123", session); // Create 2 workers for concurrent write and start them Worker worker1 = new Worker(1, cache1); Worker worker2 = new Worker(2, cache2); long start = System.currentTimeMillis(); System.out.println("Started clustering test"); worker1.start(); //worker1.join(); worker2.start(); worker1.join(); worker2.join(); long took = System.currentTimeMillis() - start; session = cache1.get("123"); System.out.println("Took: " + took + " ms. Notes count: " + session.getNotes().size() + ", failedReplaceCounter: " + failedReplaceCounter.get()); // JGroups statistics JChannel channel = (JChannel)((JGroupsTransport)cache1.getAdvancedCache().getRpcManager().getTransport()).getChannel(); System.out.println("Sent MB: " + channel.getSentBytes() / 1000000 + ", sent messages: " + channel.getSentMessages() + ", received MB: " + channel.getReceivedBytes() / 1000000 + ", received messages: " + channel.getReceivedMessages()); // Kill JVM cache1.stop(); cache2.stop(); cache1.getCacheManager().stop(); cache2.getCacheManager().stop(); System.out.println("Managers killed"); }
Example 14
Source File: TransactionalService.java From tutorials with MIT License | 4 votes |
public TransactionalService(Cache<String, Integer> transactionalCache) { this.transactionalCache = transactionalCache; transactionalCache.put(KEY, 0); }
Example 15
Source File: ClusterTest.java From hacep with Apache License 2.0 | 4 votes |
@Test public void testHASessionWithMaxBuffer() { System.setProperty("grid.buffer", "2"); LOGGER.info("Start test HASessionID with max buffer 2"); RulesConfigurationTestImpl rulesConfigurationTest = RulesTestBuilder.buildV1(); rulesConfigurationTest.registerChannel("additions", additionsChannel, replayChannel); RulesManager rulesManager = new RulesManager(rulesConfigurationTest); rulesManager.start(null, null, null); Cache<String, HAKieSession> cache1 = startNodes(2, rulesManager).getCache(); Cache<String, HAKieSession> cache2 = startNodes(2, rulesManager).getCache(); reset(replayChannel, additionsChannel); String key = "3"; HAKieSession session1 = new HAKieSession(rulesManager, executorService); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 10L)); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 20L)); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 30L)); cache1.put(key, session1); InOrder inOrder = inOrder(additionsChannel); inOrder.verify(additionsChannel, times(1)).send(eq(10L)); inOrder.verify(additionsChannel, times(1)).send(eq(30L)); inOrder.verify(additionsChannel, times(1)).send(eq(60L)); inOrder.verifyNoMoreInteractions(); // Double check on total number of calls to the method send verify(additionsChannel, times(3)).send(any()); Object serializedSessionCopy = cache2.get(key); Assert.assertNotNull(serializedSessionCopy); Assert.assertTrue(HAKieSerializedSession.class.isAssignableFrom(serializedSessionCopy.getClass())); reset(replayChannel, additionsChannel); HAKieSession session2 = ((HAKieSerializedSession) serializedSessionCopy).rebuild(); session2.insert(generateFactTenSecondsAfter(1L, 40L)); verify(additionsChannel, times(1)).send(eq(100L)); // Double check on total number of calls to the method send verify(additionsChannel, times(1)).send(any()); LOGGER.info("End test HASessionID with max buffer 2"); rulesManager.stop(); }
Example 16
Source File: TranscodingHelper.java From hibernate-demos with Apache License 2.0 | 4 votes |
public static <K, V> void putWithTranscoding(K key, V value, Cache cache) { cache.put( keyToProto( key, cache ), valueToProto( value, cache ) ); }
Example 17
Source File: TestModifiedRules.java From hacep with Apache License 2.0 | 4 votes |
@Test public void testNonEmptyHASession() throws IOException, URISyntaxException { System.setProperty("grid.buffer", "10"); logger.info("Start test modified rules"); RulesConfigurationTestImpl rulesConfigurationTest = RulesTestBuilder.buildV1(); rulesConfigurationTest.registerChannel("additions", additionsChannel, replayChannel); RulesManager rulesManager = new RulesManager(rulesConfigurationTest); rulesManager.start(null, null, null); Cache<String, Object> cache1 = startNodes(2, rulesManager).getCache(); Cache<String, Object> cache2 = startNodes(2, rulesManager).getCache(); String key = "2"; HAKieSession session1 = new HAKieSession(rulesManager, executorService); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 10L)); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 20L)); cache1.put(key, session1); verify(replayChannel, never()).send(any()); InOrder inOrder = inOrder(additionsChannel); inOrder.verify(additionsChannel, times(1)).send(eq(10L)); inOrder.verify(additionsChannel, times(1)).send(eq(30L)); inOrder.verifyNoMoreInteractions(); // Double check on total number of calls to the method send verify(additionsChannel, times(2)).send(any()); HAKieSession serializedSessionCopy = (HAKieSession) cache2.get(key); Assert.assertNotNull(serializedSessionCopy); Assert.assertTrue(serializedSessionCopy.isSerialized()); reset(replayChannel, additionsChannel); ((HAKieSerializedSession) serializedSessionCopy).createSnapshot(); ((HAKieSerializedSession) serializedSessionCopy).waitForSnapshotToComplete(); inOrder = inOrder(replayChannel); inOrder.verify(replayChannel, times(1)).send(eq(30L)); inOrder.verifyNoMoreInteractions(); reset(replayChannel, additionsChannel); rulesConfigurationTest = RulesTestBuilder.buildV1(); rulesConfigurationTest.registerChannel("additions", otherAdditionsChannel, otherReplayChannel); rulesManager = new RulesManager(rulesConfigurationTest); rulesManager.start(null, null, null); byte[] serializedSession = ((HAKieSerializedSession) serializedSessionCopy).getSerializedSession(); HAKieSession session2 = new HAKieSerializedSession(rulesManager, executorService, rulesConfigurationTest.getVersion(), serializedSession).rebuild(); String version = RulesTestBuilder.buildV2().getVersion(); rulesManager.updateToVersion(version); session2.insert(generateFactTenSecondsAfter(1L, 30L)); verify(replayChannel, never()).send(any()); verify(additionsChannel, never()).send(any()); verify(otherReplayChannel, never()).send(any()); verify(otherAdditionsChannel, atMost(1)).send(any()); verify(otherAdditionsChannel, times(1)).send(eq(120L)); logger.info("End test modified rules"); rulesManager.stop(); }
Example 18
Source File: TestPersistence.java From hacep with Apache License 2.0 | 4 votes |
@Test public void testMultiNodePersistence() throws InterruptedException { System.setProperty("grid.buffer", "10"); reset(additionsChannel, replayChannel, locksChannel); logger.info("Start test Multi Node Persistence"); RulesConfigurationTestImpl rulesConfigurationTest = RulesConfigurationTestImpl.RulesTestBuilder.buildRulesWithRetract(); rulesConfigurationTest.registerChannel("additions", additionsChannel, replayChannel); rulesConfigurationTest.registerChannel("locks", locksChannel, replayChannel); RulesManager rulesManager = new RulesManager(rulesConfigurationTest); rulesManager.start(null, null, null); nodeSelector = 1; Cache<String, Object> cache = startNodes(2, rulesManager, "A", persistenceLocation).getCache(CACHE_NAME); nodeSelector = 2; Cache<String, Object> cache2 = startNodes(2, rulesManager, "B", persistenceLocation2).getCache(CACHE_NAME); nodeSelector = 3; Cache<String, Object> cache3 = startNodes(2, rulesManager, "C", persistenceLocation3).getCache(CACHE_NAME); String key3 = "3"; HAKieSession session3 = new HAKieSession(rulesManager, executorService); // LOCK inserted expires in 25 sec. session3.insert(generateFactTenSecondsAfter(3, 10L)); cache3.put(key3, session3); String key2 = "2"; HAKieSession session2 = new HAKieSession(rulesManager, executorService); // LOCK inserted expires in 25 sec. session2.insert(generateFactTenSecondsAfter(2, 10L)); cache2.put(key2, session2); String key = "1"; HAKieSession session1 = new HAKieSession(rulesManager, executorService); // LOCK inserted expires in 25 sec. session1.insert(generateFactTenSecondsAfter(1, 10L)); cache.put(key, session1); InOrder order2 = Mockito.inOrder(additionsChannel, locksChannel); order2.verify(locksChannel, times(3)).send(eq("INSERTED")); order2.verifyNoMoreInteractions(); stopNodes(); nodeSelector = 1; Cache<String, Object> cacheDeserialized = startNodes(2, rulesManager, "A", persistenceLocation).getCache(CACHE_NAME); nodeSelector = 2; Cache<String, Object> cacheDeserialized2 = startNodes(2, rulesManager, "B", persistenceLocation2).getCache(CACHE_NAME); nodeSelector = 3; Cache<String, Object> cacheDeserialized3 = startNodes(2, rulesManager, "C", persistenceLocation3).getCache(CACHE_NAME); checkKey(key, cacheDeserialized, cacheDeserialized2, cacheDeserialized3); checkKey(key2, cacheDeserialized, cacheDeserialized2, cacheDeserialized3); checkKey(key3, cacheDeserialized, cacheDeserialized2, cacheDeserialized3); Mockito.verify( locksChannel, times(6) ).send(eq("INSERTED")); Mockito.verify( locksChannel, times(3) ).send(eq("REMOVED")); Mockito.verifyNoMoreInteractions(locksChannel); logger.info("Multi Node Persistence"); rulesManager.stop(); }
Example 19
Source File: HACEPImpl.java From hacep with Apache License 2.0 | 4 votes |
@Override public void resume() { //this.router.resume(); Cache<String, String> replicatedCache = dataGridManager.getReplicatedCache(); replicatedCache.put(Router.RESUME, String.valueOf(System.currentTimeMillis())); }
Example 20
Source File: ClusterTest.java From hacep with Apache License 2.0 | 2 votes |
@Test public void testHASessionAddNode() { System.setProperty("grid.buffer", "10"); LOGGER.info("Start test HASessionID add node"); RulesConfigurationTestImpl rulesConfigurationTest = RulesTestBuilder.buildV1(); rulesConfigurationTest.registerChannel("additions", additionsChannel, replayChannel); RulesManager rulesManager = new RulesManager(rulesConfigurationTest); rulesManager.start(null, null, null); Cache<String, HAKieSession> cache1 = startNodes(2, rulesManager).getCache(); reset(replayChannel, additionsChannel); String key = "3"; HAKieSession session1 = new HAKieSession(rulesManager, executorService); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 10L)); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 20L)); cache1.put(key, session1); session1.insert(generateFactTenSecondsAfter(1L, 30L)); cache1.put(key, session1); verify(replayChannel, never()).send(any()); InOrder inOrder = inOrder(additionsChannel); inOrder.verify(additionsChannel, times(1)).send(eq(10L)); inOrder.verify(additionsChannel, times(1)).send(eq(30L)); inOrder.verify(additionsChannel, times(1)).send(eq(60L)); inOrder.verifyNoMoreInteractions(); // Double check on total number of calls to the method send verify(additionsChannel, times(3)).send(any()); Cache<Key, HAKieSession> cache2 = startNodes(2, rulesManager).getCache(); Object serializedSessionCopy = cache2.get(key); Assert.assertNotNull(serializedSessionCopy); Assert.assertTrue(HAKieSession.class.isAssignableFrom(serializedSessionCopy.getClass())); reset(replayChannel, additionsChannel); HAKieSession session2 = ((HAKieSerializedSession) serializedSessionCopy).rebuild(); session2.insert(generateFactTenSecondsAfter(1L, 40L)); verify(replayChannel, never()).send(any()); verify(additionsChannel, times(1)).send(eq(100L)); // Double check on total number of calls to the method send verify(additionsChannel, times(1)).send(any()); LOGGER.info("End test HASessionID add node"); rulesManager.stop(); }