Java Code Examples for org.springframework.cache.Cache#get()

The following examples show how to use org.springframework.cache.Cache#get() . 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: DictUtil.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static List<Dict> getDictList() {
	Cache cache = cacheManager.getCache(CacheNameConstants.DICT_DETAILS);
	if (cache != null && cache.get(CacheNameConstants.DICT_ALL) != null) {
		return (List<Dict>) cache.get(CacheNameConstants.DICT_ALL).get();
	}
	try {
		List<Dict> dictList = dictService.findAllOrderBySort();
		if (ObjectUtil.isNotEmpty(dictList)) {
			cache.put(CacheNameConstants.DICT_ALL, dictList);
			return dictList;
		}
	} catch (Exception e) {
		log.warn("{}", e);
	}
	return null;
}
 
Example 2
Source File: AttributeValidationHelper.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected KimAttribute getAttributeDefinitionByName( String attributeName ) {
    CacheManager cm = CoreImplServiceLocator.getCacheManagerRegistry().getCacheManagerByCacheName(KimAttribute.Cache.NAME);
    Cache cache = cm.getCache(KimAttribute.Cache.NAME);
    String cacheKey = "name=" + attributeName;
    ValueWrapper valueWrapper = cache.get( cacheKey );
    
    if ( valueWrapper != null ) {
        return (KimAttribute) valueWrapper.get();
    }

    List<KimAttributeBo> attributeImpls = KradDataServiceLocator.getDataObjectService().findMatching( KimAttributeBo.class, QueryByCriteria.Builder.forAttribute(KRADPropertyConstants.ATTRIBUTE_NAME, attributeName).build()).getResults();
    KimAttribute attribute = null;
    if ( !attributeImpls.isEmpty() ) {
        attribute = KimAttributeBo.to(attributeImpls.get(0)); 
    }
    
    cache.put( cacheKey, attribute );

    return attribute;
}
 
Example 3
Source File: AbstractJCacheAnnotationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheNull() {
	Cache cache = getCache(DEFAULT_CACHE);

	String keyItem = name.getMethodName();
	assertNull(cache.get(keyItem));

	Object first = service.cacheNull(keyItem);
	Object second = service.cacheNull(keyItem);
	assertSame(first, second);

	Cache.ValueWrapper wrapper = cache.get(keyItem);
	assertNotNull(wrapper);
	assertSame(first, wrapper.get());
	assertNull("Cached value should be null", wrapper.get());
}
 
Example 4
Source File: MemcachedCacheIT.java    From memcached-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void whenFindAllThenBooksCached() {
    List<Book> books = bookService.findAll();

    assertThat(books).isNotNull();
    assertThat(bookService.getCounterFindAll()).isEqualTo(1);

    bookService.findAll();
    bookService.findAll();
    assertThat(bookService.getCounterFindAll()).isEqualTo(1);

    Cache booksCache = cacheManager.getCache("books");
    Object value = booksCache.get(SimpleKey.EMPTY);

    assertThat(value).isNotNull();
}
 
Example 5
Source File: AbstractJCacheAnnotationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void earlyPutWithExceptionVetoPut() {
	String keyItem = name.getMethodName();
	Cache cache = getCache(DEFAULT_CACHE);

	Object key = createKey(keyItem);
	Object value = new Object();
	assertNull(cache.get(key));

	try {
		service.earlyPutWithException(keyItem, value, false);
		fail("Should have thrown an exception");
	}
	catch (NullPointerException e) {
		// This is what we expect
	}
	// This will be cached anyway as the earlyPut has updated the cache before
	Cache.ValueWrapper result = cache.get(key);
	assertNotNull(result);
	assertEquals(value, result.get());
}
 
Example 6
Source File: AbstractJCacheAnnotationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void putWithException() {
	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, true);
		fail("Should have thrown an exception");
	}
	catch (UnsupportedOperationException e) {
		// This is what we expect
	}

	Cache.ValueWrapper result = cache.get(key);
	assertNotNull(result);
	assertEquals(value, result.get());
}
 
Example 7
Source File: TestTask.java    From xmanager with Apache License 2.0 6 votes vote down vote up
@Scheduled(cron = "0 59 23 * * ?")
	public void cronTest() {
		System.out.println("测试定时任务!");
		// 测试手动存储cache
		Cache cache = cacheManager.getCache("hour");
		Integer xx = cache.get("x", new Callable<Integer>() {

			@Override
			public Integer call() throws Exception {
				return 111111;
			}
			
		});
		// 测试redis
//		redisTemplate.boundListOps("xxxx").leftPush("xxxx");
		
		// 测试注解
		testService.selectById(1L);
		testService.selectById(1L);
		testService.selectById(1L);
		
		logger.debug(xx);
		logger.debug(new Date());
	}
 
Example 8
Source File: SecurityAccessMetadataSource.java    From cola-cloud with MIT License 6 votes vote down vote up
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 9
Source File: AbstractJCacheAnnotationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void earlyPutWithExceptionVetoPut() {
	String keyItem = name.getMethodName();
	Cache cache = getCache(DEFAULT_CACHE);

	Object key = createKey(keyItem);
	Object value = new Object();
	assertNull(cache.get(key));

	try {
		service.earlyPutWithException(keyItem, value, false);
		fail("Should have thrown an exception");
	}
	catch (NullPointerException e) {
		// This is what we expect
	}
	// This will be cached anyway as the earlyPut has updated the cache before
	Cache.ValueWrapper result = cache.get(key);
	assertNotNull(result);
	assertEquals(value, result.get());
}
 
Example 10
Source File: AbstractJCacheAnnotationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void earlyPutWithExceptionVetoPut() {
	String keyItem = name.getMethodName();
	Cache cache = getCache(DEFAULT_CACHE);

	Object key = createKey(keyItem);
	Object value = new Object();
	assertNull(cache.get(key));

	try {
		service.earlyPutWithException(keyItem, value, false);
		fail("Should have thrown an exception");
	}
	catch (NullPointerException e) {
		// This is what we expect
	}
	// This will be cached anyway as the earlyPut has updated the cache before
	Cache.ValueWrapper result = cache.get(key);
	assertNotNull(result);
	assertEquals(value, result.get());
}
 
Example 11
Source File: PipelineRepositoryChain.java    From piper with Apache License 2.0 5 votes vote down vote up
@Override
public Pipeline findOne(String aId) {
  Cache oneCache = cacheManager.getCache(CACHE_ONE);
  if(oneCache.get(aId)!=null) {
    return (Pipeline) oneCache.get(aId).get();
  }
  Cache allCache = cacheManager.getCache(CACHE_ALL);
  if(allCache.get(CACHE_ALL) != null) {
    List<Pipeline> pipelines = (List<Pipeline>) allCache.get(CACHE_ALL).get();
    for(Pipeline p : pipelines) {
      if(p.getId().equals(aId)) {
        return p;
      }
    }
  }
  for(PipelineRepository repository : repositories) {
    try {
      Pipeline pipeline = repository.findOne(aId);
      oneCache.put(aId, pipeline);
      return pipeline;
    }
    catch (Exception e) {
      logger.debug("{}",e.getMessage());
    }
  }
  throw new IllegalArgumentException("Unknown pipeline: " + aId);
}
 
Example 12
Source File: AbstractCacheWrapper.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected <T> T get(Cache cache, String name, Class<T> requiredType) {
    Object value = cache.get(name);
    if (value instanceof Cache.ValueWrapper) {
        value = ((Cache.ValueWrapper) value).get();
    }
    return (T) value;
}
 
Example 13
Source File: CloudUserDetailsServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 用户密码登录
 *
 * @param username 用户名
 * @return
 * @throws UsernameNotFoundException
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	Cache cache = cacheManager.getCache("user_details");
	if (cache != null && cache.get(username) != null) {
		return (CloudUser) cache.get(username).get();
	}

	SmakerResult<UserInfo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);
	UserDetails userDetails = getUserDetails(result);
	cache.put(username, userDetails);
	return userDetails;
}
 
Example 14
Source File: AbstractCacheInvoker.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Execute {@link Cache#get(Object)} on the specified {@link Cache} and
 * invoke the error handler if an exception occurs. Return {@code null}
 * if the handler does not throw any exception, which simulates a cache
 * miss in case of error.
 * @see Cache#get(Object)
 */
protected Cache.ValueWrapper doGet(Cache cache, Object key) {
	try {
		return cache.get(key);
	}
	catch (RuntimeException e) {
		getErrorHandler().handleCacheGetError(e, cache, key);
		return null; // If the exception is handled, return a cache miss
	}
}
 
Example 15
Source File: EhcacheDao.java    From web-flash with MIT License 4 votes vote down vote up
@Override
public Serializable hget(Serializable key, Serializable k) {
    Cache cache = cacheManager.getCache(String.valueOf(key));
    return cache.get(k,String.class);

}
 
Example 16
Source File: EhcacheDao.java    From web-flash with MIT License 4 votes vote down vote up
@Override
public <T>T hget(Serializable key, Serializable k,Class<T> klass) {
    Cache cache = cacheManager.getCache(String.valueOf(key));
    return cache.get(k,klass);
}
 
Example 17
Source File: ThreeLevelCacheTemplate.java    From n2o-framework with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public F execute(String firstLevelRegion, String secondLevelRegion, String thirdLevelRegion, Object firstKey,
                 Object secondKey, Object thirdKey,
                 ThreeLevelCacheCallback<F, S, T> callback) {
    Cache firstLevelCache = null;
    if (firstLevelRegion != null) {
        firstLevelCache = getCacheManager().getCache(firstLevelRegion);
        if (firstLevelCache != null) {
            Cache.ValueWrapper firstLevelCacheValueWrapper = firstLevelCache.get(firstKey);
            if (firstLevelCacheValueWrapper != null) {
                F f = (F) firstLevelCacheValueWrapper.get();
                callback.doInFirstLevelCacheHit(f);
                return f;
            }
        } else {
            log.warn(
                    "Cannot find cache named [" + firstLevelRegion + "] for ThreeLevelCacheTemplate");
        }
    }
    Cache secondLevelCache = null;
    if (secondLevelRegion != null) {
        secondLevelCache = getCacheManager().getCache(secondLevelRegion);
        if (secondLevelCache != null) {
            Cache.ValueWrapper secondLevelCacheValueWrapper = secondLevelCache.get(secondKey);
            if (secondLevelCacheValueWrapper != null) {
                S secondLevelCacheValue = (S) secondLevelCacheValueWrapper.get();
                if (secondLevelCacheValue != null) {
                    callback.doInSecondLevelCacheHit(secondLevelCacheValue);
                    return handleFirstCache(firstKey, secondLevelCacheValue, firstLevelCache, callback);
                }
            }
        } else {
            log.warn(
                    "Cannot find cache named [" + secondLevelRegion + "] for ThreeLevelCacheTemplate");
        }
    }
    Cache thirdLevelCache = null;
    if (thirdLevelRegion != null) {
        thirdLevelCache = getCacheManager().getCache(thirdLevelRegion);
        if (thirdLevelCache != null) {
            Cache.ValueWrapper thirdLevelCacheValueWrapper = thirdLevelCache.get(thirdKey);
            if (thirdLevelCacheValueWrapper != null) {
                T thirdLevelCacheValue = (T) thirdLevelCacheValueWrapper.get();
                if (thirdLevelCacheValue != null) {
                    callback.doInThirdLevelCacheHit(thirdLevelCacheValue);
                    F result = handleSecondCache(firstKey, secondKey, callback, firstLevelCache, secondLevelCache, thirdLevelCacheValue);
                    if (result != null) return result;
                }
            }
        } else {
            log.warn(
                    "Cannot find cache named [" + thirdLevelRegion + "] for ThreeLevelCacheTemplate");
        }
    }

    return handleThirdCache(firstKey, secondKey, thirdKey, callback, firstLevelCache, secondLevelCache, thirdLevelCache);
}
 
Example 18
Source File: DiscoveryClientServiceInstanceSupplier.java    From spring-cloud-loadbalancer with Apache License 2.0 4 votes vote down vote up
public List<ServiceInstance> get() {
	Cache cache = this.cacheManager.getCache("discovery-client-service-instances");
	String serviceId = getServiceId();
	return cache.get(serviceId, () -> delegate.getInstances(serviceId));
	// return delegate.getInstances(getServiceId());
}
 
Example 19
Source File: EhcacheDao.java    From flash-waimai with MIT License 4 votes vote down vote up
@Override
public <T>T hget(Serializable key, Serializable k,Class<T> klass) {
    Cache cache = cacheManager.getCache(String.valueOf(key));
    return cache.get(k,klass);
}
 
Example 20
Source File: AbstractCacheSupport.java    From springboot_cwenao with MIT License 2 votes vote down vote up
/**
 * 获取缓存内容
 * @param cache
 * @param key
 * @return
 */
protected Object getFromCache(Cache cache, String key) {
    final Cache.ValueWrapper valueWrapper = cache.get(key);
    return null == valueWrapper ? null : valueWrapper.get();
}