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

The following examples show how to use org.springframework.cache.Cache#getNativeCache() . These examples are extracted from open source projects. 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
@Override
public void run() {
    Cache cache = getCache(CacheConstants.QUERY_CACHE);
    MemcachedClientIF cacheClient = (MemcachedClientIF) cache.getNativeCache();
    Collection<SocketAddress> liveServers = cacheClient.getAvailableServers();
    Collection<SocketAddress> deadServers = cacheClient.getUnavailableServers();
    if (liveServers.isEmpty()) {
        clusterHealth.set(false);
        logger.error("All the servers in MemcachedCluster is down, UnavailableServers: " + deadServers);
    } else {
        clusterHealth.set(true);
        if (deadServers.size() > liveServers.size()) {
            logger.warn("Half of the servers in MemcachedCluster is down, LiveServers: " + liveServers
                    + ", UnavailableServers: " + deadServers);
        }
    }
}
 
Example 2
@Test
@Ignore
public void testWriteBehindPutSyncEvictSync() throws InterruptedException {
    CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class);
    Cache cache = cacheManager.getCache("writeBehindCache");
    net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
    System.out.println("cache put:" + "test");
    nativeCache.putWithWriter(new Element(1, "test"));
    System.out.println("cache get:" + cache.get(1).get());
    System.out.println("sleep:" + 2 + "s");
    Thread.sleep(2000);
    System.out.println("cache evict:" + 1);
    System.out.println("cache get:" + cache.get(1).get());
    nativeCache.removeWithWriter(1);
    System.out.println("cache get:" + cache.get(1));
    System.out.println("sleep:" + 2 + "s");
    Thread.sleep(2000);
}
 
Example 3
Source Project: api-layer   File: CacheUtils.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method read all stored records in the cache. It supports only EhCache, for other cache managers it throws
 * an exception.
 *
 * @param cacheManager manager collecting the cache
 * @param cacheName name of cache
 * @param <T> type of stored elements
 * @return collection with all stored records
 */
public <T> List<T> getAllRecords(CacheManager cacheManager, String cacheName) {
    final Cache cache = cacheManager.getCache(cacheName);
    if (cache == null) throw new IllegalArgumentException("Unknown cache " + cacheName);

    final Object nativeCache = cache.getNativeCache();
    if (nativeCache instanceof net.sf.ehcache.Cache) {
        final net.sf.ehcache.Cache ehCache = (net.sf.ehcache.Cache) nativeCache;

        return (List<T>) ehCache.getAll(ehCache.getKeys())
            .values()
            .stream()
            .map(Element::getObjectValue)
            .collect(Collectors.toList());
    } else {
        throw new IllegalArgumentException("Unsupported type of cache : " + nativeCache.getClass());
    }
}
 
Example 4
Source Project: kylin   File: MemcachedCacheManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    Cache cache = getCache(CacheConstants.QUERY_CACHE);
    MemcachedClientIF cacheClient = (MemcachedClientIF) cache.getNativeCache();
    Collection<SocketAddress> liveServers = cacheClient.getAvailableServers();
    Collection<SocketAddress> deadServers = cacheClient.getUnavailableServers();
    if (liveServers.isEmpty()) {
        clusterHealth.set(false);
        logger.error("All the servers in MemcachedCluster is down, UnavailableServers: " + deadServers);
    } else {
        clusterHealth.set(true);
        if (deadServers.size() > liveServers.size()) {
            logger.warn("Half of the servers in MemcachedCluster is down, LiveServers: " + liveServers
                    + ", UnavailableServers: " + deadServers);
        }
    }
}
 
Example 5
@Test
@Ignore
public void testWriteBehindPutEvictSync() throws InterruptedException {
    CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class);
    Cache cache = cacheManager.getCache("writeBehindCache");
    net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
    System.out.println("cache put:" + "test");
    nativeCache.putWithWriter(new Element(1, "test"));
    System.out.println("cache get:" + cache.get(1).get());
    System.out.println("cache evict:" + 1);
    nativeCache.removeWithWriter(1);
    System.out.println("sleep:" + 2 + "s");
    Thread.sleep(2000);
}
 
Example 6
@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 7
@Override
public MeterBinder getMeterBinder(Cache cache, Iterable<Tag> tags) {
   Object nativeCache = cache.getNativeCache();
   MeterBinder meterBinder = null;
   if (nativeCache instanceof org.infinispan.Cache) {
      meterBinder = new InfinispanCacheMeterBinder((org.infinispan.Cache) nativeCache, tags);
   } else {
      if (nativeCache instanceof javax.cache.Cache){ // for caches like org.infinispan.jcache.embedded.JCache
         meterBinder = new JCacheMetrics((javax.cache.Cache) nativeCache, tags);
      }
   }
   return meterBinder;
}
 
Example 8
Source Project: yes-cart   File: CacheDirectorImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<CacheInfoDTO> getCacheInfo() {
    final Collection<String> cacheNames = cacheManager.getCacheNames();
    final List<CacheInfoDTO> rez = new ArrayList<>(cacheNames.size());
    for (String cacheName : cacheNames) {
        final Cache cache = cacheManager.getCache(cacheName);
        final net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
        final CacheConfiguration cacheConfiguration = nativeCache.getCacheConfiguration();
        final StatisticsGateway stats = nativeCache.getStatistics();

        rez.add(
                new CacheInfoDTO(
                        nativeCache.getName(),
                        nativeCache.getSize(),
                        stats.getLocalHeapSize(),
                        cacheConfiguration.getMaxEntriesLocalHeap(),
                        cacheConfiguration.isOverflowToDisk(),
                        cacheConfiguration.isEternal(),
                        cacheConfiguration.getTimeToLiveSeconds(),
                        cacheConfiguration.getTimeToIdleSeconds(),
                        cacheConfiguration.getMemoryStoreEvictionPolicy().toString(),
                        stats.getLocalDiskSize(),
                        stats.getCore().get().value(CacheOperationOutcomes.GetOutcome.HIT),
                        stats.getExtended().allMiss().count().value(),
                        stats.getLocalHeapSizeInBytes(),
                        stats.getLocalDiskSizeInBytes(),
                        nativeCache.isDisabled()
                )
        );

    }
    return rez;
}
 
Example 9
Source Project: yes-cart   File: CacheDirectorImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void enableCache(final String cacheName) {
    final CacheManager cm = getCacheManager();
    final Cache cache = cm.getCache(cacheName);
    if (cache != null) {
        final net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
        nativeCache.setDisabled(false);
    }
}
 
Example 10
Source Project: yes-cart   File: CacheDirectorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void disableCache(final String cacheName) {
    final CacheManager cm = getCacheManager();
    final Cache cache = cm.getCache(cacheName);
    if (cache != null) {
        final net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
        nativeCache.setDisabled(true);
    }
}
 
Example 11
private MgmtSystemCache cacheRest(final Cache cache) {
    final Object nativeCache = cache.getNativeCache();
    if (nativeCache instanceof com.google.common.cache.Cache) {
        return guavaCache(cache, nativeCache);
    } else {
        return new MgmtSystemCache(cache.getName(), Collections.emptyList());
    }
}
 
Example 12
protected boolean isEmpty(Cache cache) {
	ConcurrentHashMap<?, ?> nativeCache = (ConcurrentHashMap<?, ?>) cache.getNativeCache();
	return nativeCache.isEmpty();
}
 
Example 13
protected boolean isEmpty(Cache cache) {
	ConcurrentHashMap<?, ?> nativeCache = (ConcurrentHashMap<?, ?>) cache.getNativeCache();
	return nativeCache.isEmpty();
}
 
Example 14
Source Project: api-layer   File: CacheUtils.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * This method evict a part of cache by condition on key if method use composite keys. It cannot be used on cache
 * with just one parameter.
 *
 * Method iterate over all keys in cache and evict just a part (if keyPredicate return true). It requires to use
 * ehCache and {@link CompositeKey}. If there is no way how to filter the entries in the cache, it will remove all
 * of them (different provider than EhCache, different type of keys).
 *
 * If entry is not stored as CompositeKey (ie. just one argumentm different keyGenerator) it will be removed allways,
 * without any test. If cache contains other entries witch CompositeKey, they will be checked and removed only in
 * case keyPredicate match.
 *
 * Example:
 *
 * <pre>
 * @Cacheable(value = "<cacheName>", keyGenerator = CacheConfig.COMPOSITE_KEY_GENERATOR)
 * public <ReturnType> cacheSomething(arg1, arg2, ...) {
 *     // do something
 *     return <value to cache>;
 * }
 *
 * @Autowired CacheManager cacheManager;
 *
 * public void evictByArg1(arg1) {
 *     CacheUtils.evictSubset(cacheManager, "<cacheName>", x -> x.equals(0, arg1));
 *     // alternatively CacheUtils.evictSubset(cacheManager, "<cacheName>", x -> ObjectUtils.equals(x.get(0), arg1));
 * }
 * </pre>
 *
 * @param cacheManager manager collecting the cache
 * @param cacheName name of cache
 * @param keyPredicate condition to filter keys to evict
 */
public void evictSubset(CacheManager cacheManager, String cacheName, Predicate<CompositeKey> keyPredicate) {
    final Cache cache = cacheManager.getCache(cacheName);
    if (cache == null) throw new IllegalArgumentException("Unknown cache " + cacheName);
    final Object nativeCache = cache.getNativeCache();
    if (nativeCache instanceof net.sf.ehcache.Cache) {
        final net.sf.ehcache.Cache ehCache = (net.sf.ehcache.Cache) nativeCache;

        for (final Object key : ehCache.getKeys()) {
            if (key instanceof CompositeKey) {
                // if entry is compositeKey and first param is different, skip it (be sure this is not to evict)
                final CompositeKey compositeKey = ((CompositeKey) key);
                if (!keyPredicate.test(compositeKey)) continue;
            }
            // if key is not composite key (unknown for evict) or has same serviceId, evict record
            ehCache.remove(key);
        }
    } else {
        // in case of using different cache manager, evict all records for sure
        cache.clear();
    }
}
 
Example 15
protected boolean isEmpty(Cache cache) {
	ConcurrentHashMap<?, ?> nativeCache = (ConcurrentHashMap<?, ?>) cache.getNativeCache();
	return nativeCache.isEmpty();
}