org.springframework.cache.Cache Java Examples
The following examples show how to use
org.springframework.cache.Cache.
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: AbstractCacheManager.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public Cache getCache(String name) { Cache cache = this.cacheMap.get(name); if (cache != null) { return cache; } else { // Fully synchronize now for missing cache creation... synchronized (this.cacheMap) { cache = this.cacheMap.get(name); if (cache == null) { cache = getMissingCache(name); if (cache != null) { cache = decorateCache(cache); this.cacheMap.put(name, cache); updateCacheNames(name); } } return cache; } } }
Example #2
Source File: AbstractJCacheAnnotationTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void putWithExceptionVetoPut() { String keyItem = name.getMethodName(); Cache cache = getCache(DEFAULT_CACHE); Object key = createKey(keyItem); Object value = new Object(); assertNull(cache.get(key)); try { service.putWithException(keyItem, value, false); fail("Should have thrown an exception"); } catch (NullPointerException e) { // This is what we expect } assertNull(cache.get(key)); }
Example #3
Source File: AbstractGenericCacheWrapper.java From entando-core with GNU Lesser General Public License v3.0 | 6 votes |
protected <O> void manage(String key, O object, Action operation) { if (null == object) { return; } Cache cache = this.getCache(); List<String> codes = (List<String>) this.get(cache, this.getCodesCacheKey(), List.class); if (Action.ADD.equals(operation)) { if (!codes.contains(key)) { codes.add(key); cache.put(this.getCodesCacheKey(), codes); } cache.put(this.getCacheKeyPrefix() + key, object); } else if (Action.UPDATE.equals(operation)) { if (!codes.contains(key)) { throw new CacheItemNotFoundException(key, cache.getName()); } cache.put(this.getCacheKeyPrefix() + key, object); } else if (Action.DELETE.equals(operation)) { codes.remove(key); cache.evict(this.getCacheKeyPrefix() + key); cache.put(this.getCodesCacheKey(), codes); } }
Example #4
Source File: ResilientCartRepositoryImplTest.java From yes-cart with Apache License 2.0 | 6 votes |
@Test public void testGetShoppingCartNullOrEmptyToken() throws Exception { final ShoppingCartStateService shoppingCartStateService = context.mock(ShoppingCartStateService.class, "shoppingCartStateService"); final ShopService shopService = context.mock(ShopService.class, "shopService"); final CartUpdateProcessor cartUpdateProcessor = context.mock(CartUpdateProcessor.class, "cartUpdateProcessor"); final TaskExecutor taskExecutor = context.mock(TaskExecutor.class, "taskExecutor"); final CacheManager cacheManager = context.mock(CacheManager.class, "cacheManager"); final Cache cartCache = context.mock(Cache.class, "cartCache"); context.checking(new Expectations() {{ oneOf(cacheManager).getCache("web.shoppingCart"); will(returnValue(cartCache)); }}); final ResilientCartRepositoryImpl repo = new ResilientCartRepositoryImpl(shoppingCartStateService, shopService, cartUpdateProcessor, mockCartSerDes, 60, cacheManager, taskExecutor); assertNull(repo.getShoppingCart(null)); assertNull(repo.getShoppingCart(" ")); context.assertIsSatisfied(); }
Example #5
Source File: CacheAspectSupport.java From spring-analysis-note with MIT License | 6 votes |
private void performCacheEvict( CacheOperationContext context, CacheEvictOperation operation, @Nullable Object result) { Object key = null; for (Cache cache : context.getCaches()) { if (operation.isCacheWide()) { logInvalidating(context, operation, null); doClear(cache); } else { if (key == null) { key = generateKey(context, result); } logInvalidating(context, operation, key); doEvict(cache, key); } } }
Example #6
Source File: AbstractJCacheAnnotationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void cacheCheckedException() { String keyItem = name.getMethodName(); Cache cache = getCache(EXCEPTION_CACHE); Object key = createKey(keyItem); assertNull(cache.get(key)); try { service.cacheWithCheckedException(keyItem, true); fail("Should have thrown an exception"); } catch (IOException e) { // This is what we expect } Cache.ValueWrapper result = cache.get(key); assertNotNull(result); assertEquals(IOException.class, result.get().getClass()); }
Example #7
Source File: AbstractJCacheAnnotationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void earlyRemoveAllWithException() { Cache cache = getCache(DEFAULT_CACHE); Object key = createKey(name.getMethodName()); cache.put(key, new Object()); try { service.earlyRemoveAllWithException(true); fail("Should have thrown an exception"); } catch (UnsupportedOperationException e) { // This is what we expect } assertTrue(isEmpty(cache)); }
Example #8
Source File: ElastiCacheCachingConfigurationTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void enableElasticache_configuredWithExplicitCluster_configuresExplicitlyConfiguredCaches() throws Exception { // Arrange // Act this.context = new AnnotationConfigApplicationContext( ApplicationConfigurationWithExplicitStackConfiguration.class); // Assert CacheManager cacheManager = this.context.getBean(CachingConfigurer.class) .cacheManager(); assertThat(cacheManager.getCacheNames().size()).isEqualTo(2); Cache firstCache = cacheManager.getCache("firstCache"); assertThat(firstCache.getName()).isNotNull(); assertThat(getExpirationFromCache(firstCache)).isEqualTo(0); Cache secondCache = cacheManager.getCache("secondCache"); assertThat(secondCache.getName()).isNotNull(); assertThat(getExpirationFromCache(secondCache)).isEqualTo(0); }
Example #9
Source File: AspectJCacheAnnotationTests.java From java-technology-stack with MIT License | 6 votes |
@Override public void testMultiEvict(CacheableService<?> service) { Object o1 = new Object(); Object r1 = service.multiCache(o1); Object r2 = service.multiCache(o1); Cache primary = cm.getCache("primary"); Cache secondary = cm.getCache("secondary"); assertSame(r1, r2); assertSame(r1, primary.get(o1).get()); assertSame(r1, secondary.get(o1).get()); service.multiEvict(o1); assertNull(primary.get(o1)); assertNull(secondary.get(o1)); Object r3 = service.multiCache(o1); Object r4 = service.multiCache(o1); assertNotSame(r1, r3); assertSame(r3, r4); assertSame(r3, primary.get(o1).get()); assertSame(r4, secondary.get(o1).get()); }
Example #10
Source File: SecurityAccessMetadataSource.java From cola-cloud with MIT License | 6 votes |
public void loadUrlRoleMapping() { if(metadata != null){ metadata.clear(); }else{ this.metadata = new HashMap<>(); } //从缓存中获取数据 Cache cache = cacheManager.getCache(ResourceCacheConstant.URL_ROLE_MAPPING_CACHE); Cache.ValueWrapper valueWrapper = cache.get(serviceId); Map<String, Set<String>> urlRoleMapping = null; if (valueWrapper != null) { urlRoleMapping = (Map<String, Set<String>>) valueWrapper.get(); } //组装SpringSecurrty的数据 if (urlRoleMapping != null) { for (Map.Entry<String, Set<String>> entry : urlRoleMapping.entrySet()) { Set<String> roleCodes = entry.getValue(); Collection<ConfigAttribute> configs = CollectionUtils.collect(roleCodes.iterator(), input -> new SecurityConfig(input)); this.metadata.put(entry.getKey(), configs); } } }
Example #11
Source File: SafeCache.java From icure-backend with GNU General Public License v2.0 | 6 votes |
public V get(K key, ValueProvider<K, V> valueProvider) { V value; Cache.ValueWrapper valueWrapper = cache.get(key); if (valueWrapper == null) { synchronized (this) { valueWrapper = cache.get(key); if (valueWrapper == null) { value = valueProvider.getValue(key); cache.put(key, value); } else { value = (V) valueWrapper.get(); } } } else { value = (V) valueWrapper.get(); } return value; }
Example #12
Source File: RolloutStatusCache.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
private List<TotalTargetCountActionStatus> retrieveFromCache(final Long id, final Cache cache) { final CachedTotalTargetCountActionStatus cacheItem = cache.get(id, CachedTotalTargetCountActionStatus.class); if (cacheItem == null) { return Collections.emptyList(); } return cacheItem.getStatus(); }
Example #13
Source File: ApiResourceCacheWrapper.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void initCache(Map<String, ApiResource> resources, IApiCatalogDAO apiCatalogDAO) throws ApsSystemException { try { Cache cache = this.getCache(); this.releaseCachedObjects(cache); apiCatalogDAO.loadApiStatus(resources); this.insertObjectsOnCache(cache, resources); } catch (Throwable t) { logger.error("Error bootstrapping ApiCatalog cache", t); throw new ApsSystemException("Error bootstrapping ApiCatalog cache", t); } }
Example #14
Source File: CacheResultInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override protected Object invoke(CacheOperationInvocationContext<CacheResultOperation> context, CacheOperationInvoker invoker) { CacheResultOperation operation = context.getOperation(); Object cacheKey = generateKey(context); Cache cache = resolveCache(context); Cache exceptionCache = resolveExceptionCache(context); if (!operation.isAlwaysInvoked()) { Cache.ValueWrapper cachedValue = doGet(cache, cacheKey); if (cachedValue != null) { return cachedValue.get(); } checkForCachedException(exceptionCache, cacheKey); } try { Object invocationResult = invoker.invoke(); cache.put(cacheKey, invocationResult); return invocationResult; } catch (CacheOperationInvoker.ThrowableWrapper ex) { Throwable original = ex.getOriginal(); cacheException(exceptionCache, operation.getExceptionTypeFilter(), cacheKey, original); throw ex; } }
Example #15
Source File: ApiServiceCacheWrapper.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void initCache(Map<String, ApiResource> resources, IApiCatalogDAO apiCatalogDAO) throws ApsSystemException { try { Cache cache = this.getCache(); this.releaseCachedObjects(cache); List<ApiMethod> apiGETMethods = buildApiGetMethods(resources); Map<String, ApiService> services = apiCatalogDAO.loadServices(apiGETMethods); this.insertObjectsOnCache(cache, services); } catch (Throwable t) { logger.error("Error bootstrapping ApiCatalog cache", t); throw new ApsSystemException("Error bootstrapping ApiCatalog cache", t); } }
Example #16
Source File: GuavaCacheManagerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void changeCacheLoaderRecreateCache() { GuavaCacheManager cm = new GuavaCacheManager("c1"); Cache cache1 = cm.getCache("c1"); CacheLoader<Object,Object> loader = mockCacheLoader(); cm.setCacheLoader(loader); Cache cache1x = cm.getCache("c1"); assertTrue(cache1x != cache1); cm.setCacheLoader(loader); // Set same instance Cache cache1xx = cm.getCache("c1"); assertSame(cache1x, cache1xx); }
Example #17
Source File: SyncTwoLevelCacheTemplate.java From n2o-framework with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override protected S handleSecondCache(String key, TwoLevelCacheCallback<F, S> callback, Cache secondLevelCache) { synchronized (key.intern()) { //еще раз читаем, т.к. в кэш могли положить пока ждали Cache.ValueWrapper valueWrapper = secondLevelCache.get(key); if (valueWrapper != null) { S value = (S) valueWrapper.get(); callback.doInSecondLevelCacheHit(value); return value; } return super.handleSecondCache(key, callback, secondLevelCache); } }
Example #18
Source File: AbstractJCacheAnnotationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void cacheWithCustomCacheResolver() { String keyItem = name.getMethodName(); Cache cache = getCache(DEFAULT_CACHE); Object key = createKey(keyItem); service.cacheWithCustomCacheResolver(keyItem); assertNull(cache.get(key)); // Cache in mock cache }
Example #19
Source File: AbstractCacheInvoker.java From java-technology-stack with MIT License | 5 votes |
/** * Execute {@link Cache#put(Object, Object)} on the specified {@link Cache} * and invoke the error handler if an exception occurs. */ protected void doPut(Cache cache, Object key, @Nullable Object result) { try { cache.put(key, result); } catch (RuntimeException ex) { getErrorHandler().handleCachePutError(ex, cache, key, result); } }
Example #20
Source File: JCacheCacheManager.java From lams with GNU General Public License v2.0 | 5 votes |
@Override protected Collection<Cache> loadCaches() { Collection<Cache> caches = new LinkedHashSet<Cache>(); for (String cacheName : getCacheManager().getCacheNames()) { javax.cache.Cache<Object, Object> jcache = getCacheManager().getCache(cacheName); caches.add(new JCacheCache(jcache, isAllowNullValues())); } return caches; }
Example #21
Source File: CacheResolverAdapterTests.java From java-technology-stack with MIT License | 5 votes |
protected CacheResolver getCacheResolver(CacheInvocationContext<? extends Annotation> context, String cacheName) { CacheResolver cacheResolver = mock(CacheResolver.class); javax.cache.Cache cache; if (cacheName == null) { cache = null; } else { cache = mock(javax.cache.Cache.class); given(cache.getName()).willReturn(cacheName); } given(cacheResolver.resolveCache(context)).willReturn(cache); return cacheResolver; }
Example #22
Source File: GuavaCacheManagerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void changeCacheSpecificationRecreateCache() { GuavaCacheManager cm = new GuavaCacheManager("c1"); Cache cache1 = cm.getCache("c1"); CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().maximumSize(10); cm.setCacheBuilder(cacheBuilder); Cache cache1x = cm.getCache("c1"); assertTrue(cache1x != cache1); cm.setCacheBuilder(cacheBuilder); // Set same instance Cache cache1xx = cm.getCache("c1"); assertSame(cache1x, cache1xx); }
Example #23
Source File: PermissionServiceImpl.java From rice with Educational Community License v2.0 | 5 votes |
/** * Compare each of the passed in permissions with the given permissionDetails. Those that * match are added to the result list. */ protected List<Permission> getMatchingPermissions( List<Permission> permissions, Map<String, String> permissionDetails ) { List<String> permissionIds = new ArrayList<String>(permissions.size()); for (Permission permission : permissions) { permissionIds.add(permission.getId()); } String cacheKey = new StringBuilder("{getMatchingPermissions}") .append("permissionIds=").append(CacheKeyUtils.key(permissionIds)).append("|") .append("permissionDetails=").append(CacheKeyUtils.mapKey(permissionDetails)).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } List<Permission> applicablePermissions = new ArrayList<Permission>(); if ( permissionDetails == null || permissionDetails.isEmpty() ) { // if no details passed, assume that all match for ( Permission perm : permissions ) { applicablePermissions.add(perm); } } else { // otherwise, attempt to match the permission details // build a map of the template IDs to the type services Map<String,PermissionTypeService> permissionTypeServices = getPermissionTypeServicesByTemplateId(permissions); // build a map of permissions by template ID Map<String, List<Permission>> permissionMap = groupPermissionsByTemplate(permissions); // loop over the different templates, matching all of the same template against the type // service at once for ( Map.Entry<String,List<Permission>> entry : permissionMap.entrySet() ) { PermissionTypeService permissionTypeService = permissionTypeServices.get( entry.getKey() ); List<Permission> permissionList = entry.getValue(); applicablePermissions.addAll( permissionTypeService.getMatchingPermissions( permissionDetails, permissionList ) ); } } applicablePermissions = Collections.unmodifiableList(applicablePermissions); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, applicablePermissions); return applicablePermissions; }
Example #24
Source File: ArcusCacheManager.java From arcus-spring with Apache License 2.0 | 5 votes |
@Override protected Collection<? extends Cache> loadCaches() { List<Cache> caches = new ArrayList<Cache>(initialCacheConfigs.size()); for (Map.Entry<String, ArcusCacheConfiguration> entry : initialCacheConfigs.entrySet()) { caches.add( createCache(entry.getKey(), entry.getValue())); } return caches; }
Example #25
Source File: RoleServiceImpl.java From rice with Educational Community License v2.0 | 5 votes |
protected Role getRoleFromCache(String namespaceCode, String name) { Cache cache = cacheManager.getCache(Role.Cache.NAME); Cache.ValueWrapper cachedValue = cache.get("namespaceCode=" + namespaceCode + "|name=" + name); if (cachedValue != null) { return (Role) cachedValue.get(); } return null; }
Example #26
Source File: ConcurrentMapCacheManagerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testDynamicMode() { CacheManager cm = new ConcurrentMapCacheManager(); Cache cache1 = cm.getCache("c1"); assertTrue(cache1 instanceof ConcurrentMapCache); Cache cache1again = cm.getCache("c1"); assertSame(cache1again, cache1); Cache cache2 = cm.getCache("c2"); assertTrue(cache2 instanceof ConcurrentMapCache); Cache cache2again = cm.getCache("c2"); assertSame(cache2again, cache2); Cache cache3 = cm.getCache("c3"); assertTrue(cache3 instanceof ConcurrentMapCache); Cache cache3again = cm.getCache("c3"); assertSame(cache3again, cache3); cache1.put("key1", "value1"); assertEquals("value1", cache1.get("key1").get()); cache1.put("key2", 2); assertEquals(2, cache1.get("key2").get()); cache1.put("key3", null); assertNull(cache1.get("key3").get()); cache1.put("key3", null); assertNull(cache1.get("key3").get()); cache1.evict("key3"); assertNull(cache1.get("key3")); assertEquals("value1", cache1.putIfAbsent("key1", "value1x").get()); assertEquals("value1", cache1.get("key1").get()); assertEquals(2, cache1.putIfAbsent("key2", 2.1).get()); assertNull(cache1.putIfAbsent("key3", null)); assertNull(cache1.get("key3").get()); assertNull(cache1.putIfAbsent("key3", null).get()); assertNull(cache1.get("key3").get()); cache1.evict("key3"); assertNull(cache1.get("key3")); }
Example #27
Source File: AbstractCacheInterceptor.java From spring-analysis-note with MIT License | 5 votes |
/** * Convert the collection of caches in a single expected element. * <p>Throw an {@link IllegalStateException} if the collection holds more than one element * @return the single element or {@code null} if the collection is empty */ @Nullable static Cache extractFrom(Collection<? extends Cache> caches) { if (CollectionUtils.isEmpty(caches)) { return null; } else if (caches.size() == 1) { return caches.iterator().next(); } else { throw new IllegalStateException("Unsupported cache resolution result " + caches + ": JSR-107 only supports a single cache."); } }
Example #28
Source File: ResilientCartRepositoryImplTest.java From yes-cart with Apache License 2.0 | 5 votes |
@Test public void testGetShoppingCartFromCacheLoggedOutInactive() throws Exception { final ShoppingCartStateService shoppingCartStateService = context.mock(ShoppingCartStateService.class, "shoppingCartStateService"); final ShopService shopService = context.mock(ShopService.class, "shopService"); final CartUpdateProcessor cartUpdateProcessor = context.mock(CartUpdateProcessor.class, "cartUpdateProcessor"); final TaskExecutor taskExecutor = context.mock(TaskExecutor.class, "taskExecutor"); final CacheManager cacheManager = context.mock(CacheManager.class, "cacheManager"); final Cache cartCache = context.mock(Cache.class, "cartCache"); final Cache.ValueWrapper wrapper = context.mock(Cache.ValueWrapper.class, "wrapper"); final ShoppingCart cachedCart = context.mock(ShoppingCart.class, "cachedCart"); final byte[] cached = new byte[0]; context.checking(new Expectations() {{ oneOf(cacheManager).getCache("web.shoppingCart"); will(returnValue(cartCache)); oneOf(cartCache).get("IN-CACHE"); will(returnValue(wrapper)); oneOf(wrapper).get(); will(returnValue(cached)); oneOf(mockCartSerDes).restoreState(cached); will(returnValue(cachedCart)); allowing(cachedCart).getLogonState(); will(returnValue(ShoppingCart.SESSION_EXPIRED)); }}); final ResilientCartRepositoryImpl repo = new ResilientCartRepositoryImpl(shoppingCartStateService, shopService, cartUpdateProcessor, mockCartSerDes, 60, cacheManager, taskExecutor); assertEquals(cachedCart, repo.getShoppingCart("IN-CACHE")); context.assertIsSatisfied(); }
Example #29
Source File: AbstractCacheInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Convert the collection of caches in a single expected element. * <p>Throw an {@link IllegalStateException} if the collection holds more than one element * @return the singe element or {@code null} if the collection is empty */ static Cache extractFrom(Collection<? extends Cache> caches) { if (CollectionUtils.isEmpty(caches)) { return null; } else if (caches.size() == 1) { return caches.iterator().next(); } else { throw new IllegalStateException("Unsupported cache resolution result " + caches + ": JSR-107 only supports a single cache."); } }
Example #30
Source File: EnableCachingIntegrationTests.java From java-technology-stack with MIT License | 5 votes |
private void fooGetSimple(FooService service) { Cache cache = getCache(); Object key = new Object(); assertCacheMiss(key, cache); Object value = service.getSimple(key); assertCacheHit(key, value, cache); }