當前位置: 首頁>>代碼示例>>Java>>正文


Java Cache類代碼示例

本文整理匯總了Java中javax.cache.Cache的典型用法代碼示例。如果您正苦於以下問題:Java Cache類的具體用法?Java Cache怎麽用?Java Cache使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Cache類屬於javax.cache包,在下文中一共展示了Cache類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getCache

import javax.cache.Cache; //導入依賴的package包/類
@Override
public <K, V> Cache<K, V> getCache(String cacheName, Class<K> keyType, Class<V> valueType) {
    checkNotClosed();
    if (cacheName == null) {
        throw new NullPointerException();
    }
    if (keyType == null) {
        throw new NullPointerException();
    }
    if (valueType == null) {
        throw new NullPointerException();
    }
    
    JCache<?, ?> cache = caches.get(cacheName);
    if (cache == null) {
        return null;
    }
    
    if (!keyType.isAssignableFrom(cache.getConfiguration(CompleteConfiguration.class).getKeyType())) {
        throw new ClassCastException("Wrong type of key for " + cacheName);
    }
    if (!valueType.isAssignableFrom(cache.getConfiguration(CompleteConfiguration.class).getValueType())) {
        throw new ClassCastException("Wrong type of value for " + cacheName);
    }
    return (Cache<K, V>) cache;
}
 
開發者ID:qq1588518,項目名稱:JRediClients,代碼行數:27,代碼來源:JCacheManager.java

示例2: close

import javax.cache.Cache; //導入依賴的package包/類
@Override
public void close() {
    if (isClosed()) {
        return;
    }

    synchronized (cacheProvider) {
        if (!isClosed()) {
            cacheProvider.close(uri, classLoader);
            for (Cache<?, ?> cache : caches.values()) {
                try {
                    cache.close();
                } catch (Exception e) {
                    // skip
                }
            }
            redisson.shutdown();
            closed = true;
        }
    }
}
 
開發者ID:qq1588518,項目名稱:JRediClients,代碼行數:22,代碼來源:JCacheManager.java

示例3: testRedissonConfig

import javax.cache.Cache; //導入依賴的package包/類
@Test
public void testRedissonConfig() throws InterruptedException, IllegalArgumentException, URISyntaxException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);
    
    cache.put("1", "2");
    Assert.assertEquals("2", cache.get("1"));
    
    cache.close();
    runner.stop();
}
 
開發者ID:qq1588518,項目名稱:JRediClients,代碼行數:22,代碼來源:JCacheTest.java

示例4: update

import javax.cache.Cache; //導入依賴的package包/類
/**
 * @param cacheName Cache name.
 * @param fun An operation that accepts a cache entry and processes it.
 * @param ignite Ignite.
 * @param keysGen Keys generator.
 * @param <K> Cache key object type.
 * @param <V> Cache value object type.
 */
public static <K, V> void update(String cacheName, Ignite ignite, IgniteConsumer<Cache.Entry<K, V>> fun,
    IgniteSupplier<Set<K>> keysGen) {
    bcast(cacheName, ignite, () -> {
        Ignite ig = Ignition.localIgnite();
        IgniteCache<K, V> cache = ig.getOrCreateCache(cacheName);

        Affinity<K> affinity = ig.affinity(cacheName);
        ClusterNode locNode = ig.cluster().localNode();

        Collection<K> ks = affinity.mapKeysToNodes(keysGen.get()).get(locNode);

        if (ks == null)
            return;

        Map<K, V> m = new ConcurrentHashMap<>();

        for (K k : ks) {
            V v = cache.localPeek(k);
            fun.accept(new CacheEntryImpl<>(k, v));
            m.put(k, v);
        }

        cache.putAll(m);
    });
}
 
開發者ID:Luodian,項目名稱:Higher-Cloud-Computing-Project,代碼行數:34,代碼來源:CacheUtils.java

示例5: run

import javax.cache.Cache; //導入依賴的package包/類
@Override
public CommandOutcome run(Cli cli) {

    //retrieve the cache defined in the declaration file hazelcast.xml
    Cache<String, Integer> declarativeCache = cacheManager.get()
            .getCache("myCache1", String.class, Integer.class);

    //put an entry...
    //CacheEntryCreatedListener fires afterwards
    declarativeCache.put("1", 1);

    //retrieve the cache configured programmatically and contributed into Bootique
    Cache<String, String> programmaticCache = cacheManager.get()
            .getCache("myCache2", String.class, String.class);

    //put an entry...
    //CacheEntryCreatedListener fires afterwards
    programmaticCache.put("key1", "value1");

    return CommandOutcome.succeeded();
}
 
開發者ID:bootique-examples,項目名稱:bootique-jcache-demo,代碼行數:22,代碼來源:DemoHazelcastCommand.java

示例6: run

import javax.cache.Cache; //導入依賴的package包/類
@Override
public CommandOutcome run(Cli cli) {

    //retrieve the cache defined in ehcache.xml
    Cache<String, Integer> cache = cacheManager.get()
            .getCache("myCache1", String.class, Integer.class);

    //put an entry...
    //CacheEntryCreatedListener fires afterwards
    cache.put("1", 1);

    //retrieve the cache configured programmatically and contributed into Bootique
    Cache<Long, Long> myCache2 = cacheManager.get()
            .getCache("myCache2", Long.class, Long.class);

    //put an entry...
    //CacheEntryCreatedListener fires afterwards
    myCache2.put(1L, 1L);

    return CommandOutcome.succeeded();
}
 
開發者ID:bootique-examples,項目名稱:bootique-jcache-demo,代碼行數:22,代碼來源:DemoEhcacheCommand.java

示例7: getSumsAndCounts

import javax.cache.Cache; //導入依賴的package包/類
/** */
private SumsAndCounts getSumsAndCounts(Vector[] centers, int dim, UUID uid, String cacheName) {
    return CacheUtils.distributedFold(cacheName,
        (IgniteBiFunction<Cache.Entry<SparseMatrixKey, Map<Integer, Double>>, SumsAndCounts, SumsAndCounts>)(entry, counts) -> {
            Map<Integer, Double> vec = entry.getValue();

            IgniteBiTuple<Integer, Double> closest = findClosest(centers, VectorUtils.fromMap(vec, false));
            int bestCenterIdx = closest.get1();

            counts.totalCost += closest.get2();
            counts.sums.putIfAbsent(bestCenterIdx, VectorUtils.zeroes(dim));

            counts.sums.compute(bestCenterIdx,
                (IgniteBiFunction<Integer, Vector, Vector>)(ind, v) -> v.plus(VectorUtils.fromMap(vec, false)));

            counts.counts.merge(bestCenterIdx, 1,
                (IgniteBiFunction<Integer, Integer, Integer>)(i1, i2) -> i1 + i2);

            return counts;
        },
        key -> key.dataStructureId().equals(uid),
        SumsAndCounts::merge, SumsAndCounts::new
    );
}
 
開發者ID:Luodian,項目名稱:Higher-Cloud-Computing-Project,代碼行數:25,代碼來源:KMeansDistributedClusterer.java

示例8: cleanExpiredRecords

import javax.cache.Cache; //導入依賴的package包/類
@Scheduled(initialDelayString = "${initialDelay}", fixedDelayString = "${fixedDelay}")
public void cleanExpiredRecords(){
    // query the matching records first
    logger.debug("Starting the clean up job to clear the expired records");
    long towMinutesRange = System.currentTimeMillis()-900000;
    final IgniteCache<String, List<AlertEntry>> alertsCache = getAlertsCache();
    final String sql = "select * from AlertEntry where timestamp <= ?";
    SqlQuery<String,AlertEntry> query = new SqlQuery(AlertEntry.class,sql);
    query.setArgs(towMinutesRange);
    final List<Cache.Entry<String, AlertEntry>> toDeleteAlerts = alertsCache.query(query).getAll();
    // then call remove all as this will remove the records from the cache and the persistent file system as sql delete will just delete it from the cache layer not the file system
    // or the persistent store
    if(toDeleteAlerts!=null && !toDeleteAlerts.isEmpty()){
        logger.debug("Finished cleaning out {} records",toDeleteAlerts.size());
        alertsCache.removeAll(new HashSet(toDeleteAlerts
                .stream()
                .map(Cache.Entry::getKey)
                .collect(Collectors.toList())));

    }

}
 
開發者ID:Romeh,項目名稱:spring-boot-ignite,代碼行數:23,代碼來源:CleanExpiredAlertsService.java

示例9: getNewCenters

import javax.cache.Cache; //導入依賴的package包/類
/**
 * Choose some number of center candidates from source points according to their costs.
 *
 * @param cacheName Cache name of point matrix.
 * @param uuid Uuid of point matrix.
 * @param costs Hash map with costs (distances to nearest center).
 * @param costsSum The sum of costs.
 * @param k The estimated number of centers.
 * @return The list of new candidates.
 */
private List<Vector> getNewCenters(String cacheName, UUID uuid,
                                   ConcurrentHashMap<Integer, Double> costs, double costsSum, int k) {
    return CacheUtils.distributedFold(cacheName,
            (IgniteBiFunction<Cache.Entry<SparseMatrixKey, Map<Integer, Double>>,
                              List<Vector>,
                              List<Vector>>)(vectorWithIndex, centers) -> {
                Integer idx = vectorWithIndex.getKey().index();
                Vector vector = VectorUtils.fromMap(vectorWithIndex.getValue(), false);

                double probability = (costs.get(idx) * 2.0 * k) / costsSum;

                if (rnd.nextDouble() < probability)
                    centers.add(vector);

                return centers;
            },
            key -> key.dataStructureId().equals(uuid),
            (list1, list2) -> {
                list1.addAll(list2);
                return list1;
            },
            ArrayList::new);
}
 
開發者ID:Luodian,項目名稱:Higher-Cloud-Computing-Project,代碼行數:34,代碼來源:FuzzyCMeansDistributedClusterer.java

示例10: JCacheMetrics

import javax.cache.Cache; //導入依賴的package包/類
public JCacheMetrics(Cache<?, ?> cache, String name, Iterable<Tag> tags) {
    try {
        String cacheManagerUri = cache.getCacheManager().getURI().toString()
            .replace(':', '.'); // ehcache's uri is prefixed with 'urn:'

        this.objectName = new ObjectName("javax.cache:type=CacheStatistics"
            + ",CacheManager=" + cacheManagerUri
            + ",Cache=" + cache.getName());
    } catch (MalformedObjectNameException ignored) {
        throw new IllegalStateException("Cache name '" + cache.getName() + "' results in an invalid JMX name");
    }
    this.name = name;
    this.tags = Tags.concat(tags, "name", cache.getName());
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:15,代碼來源:JCacheMetrics.java

示例11: cacheExposesMetrics

import javax.cache.Cache; //導入依賴的package包/類
@ParameterizedTest
@MethodSource("cachingProviders")
void cacheExposesMetrics(CachingProvider provider) {
    CacheManager cacheManager = provider.getCacheManager();

    MutableConfiguration<Integer, String> configuration = new MutableConfiguration<>();
    configuration.setTypes(Integer.class, String.class)
        .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR))
        .setStatisticsEnabled(true);

    Cache<Integer, String> cache = cacheManager.createCache("a", configuration);
    cache.put(1, "test");

    MeterRegistry registry = new SimpleMeterRegistry();
    JCacheMetrics.monitor(registry, cache, "jcache", emptyList());

    assertThat(registry.mustFind("jcache.puts").tags("name", "a").gauge().value()).isEqualTo(1.0);
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:19,代碼來源:JCacheMetricsTest.java

示例12: onAfterPut

import javax.cache.Cache; //導入依賴的package包/類
@Override
public void onAfterPut(Cache.Entry<Long, JournalItem> entry) {
    IgniteCache<String, Long> sequenceNumberTrack = ignite.getOrCreateCache("sequenceNumberTrack");
    sequenceNumberTrack.invoke(entry.getValue().getPersistenceId(), (mutableEntry, objects) -> {
        if (mutableEntry.exists() && mutableEntry.getValue() != null) {
            // if it is less than the new sequence value , use it
            if (mutableEntry.getValue() < entry.getKey()) {
                mutableEntry.setValue(entry.getKey());
            }
        } else {
            // if does not exist , just use it
            mutableEntry.setValue(entry.getKey());
        }
        // by api design nothing needed here
        return null;
    });
}
 
開發者ID:Romeh,項目名稱:akka-persistance-ignite,代碼行數:18,代碼來源:JournalStoreInterceptor.java

示例13: CacheColumnDecisionTreeTrainerInput

import javax.cache.Cache; //導入依賴的package包/類
/**
 * Constructs input for {@link ColumnDecisionTreeTrainer}.
 *
 * @param c Cache.
 * @param valuesMapper Function for mapping cache entry to stream used by {@link ColumnDecisionTreeTrainer}.
 * @param labelsMapper Function used for mapping cache value to labels array.
 * @param keyMapper Function used for mapping feature index to the cache key.
 * @param catFeaturesInfo Information about which features are categorical in form of feature index -> number of
 * categories.
 * @param featuresCnt Count of features.
 * @param samplesCnt Count of samples.
 */
// TODO: IGNITE-5724 think about boxing/unboxing
public CacheColumnDecisionTreeTrainerInput(IgniteCache<K, V> c,
    IgniteSupplier<Stream<K>> labelsKeys,
    IgniteFunction<Cache.Entry<K, V>, Stream<IgniteBiTuple<Integer, Double>>> valuesMapper,
    IgniteFunction<V, DoubleStream> labelsMapper,
    IgniteFunction<Integer, Stream<K>> keyMapper,
    Map<Integer, Integer> catFeaturesInfo,
    int featuresCnt, int samplesCnt) {

    cacheName = c.getName();
    this.labelsKeys = labelsKeys;
    this.valuesMapper = valuesMapper;
    this.labelsMapper = labelsMapper;
    this.keyMapper = keyMapper;
    this.catFeaturesInfo = catFeaturesInfo;
    this.samplesCnt = samplesCnt;
    this.featuresCnt = featuresCnt;
}
 
開發者ID:Luodian,項目名稱:Higher-Cloud-Computing-Project,代碼行數:31,代碼來源:CacheColumnDecisionTreeTrainerInput.java

示例14: getBuffer

import javax.cache.Cache; //導入依賴的package包/類
/**
 * Gets buffer which holds changes for specific cache made during transaction.
 *
 * @return buffer.
 */
private Collection<Cache.Entry<?, ?>> getBuffer() {
    Map<Object, Object> properties = session.properties();
    Set<String> caches = (Set<String>) properties.get(CACHES_PROPERTY_NAME);
    if (caches == null) {
        properties.put(CACHES_PROPERTY_NAME, caches = new HashSet<>());
        properties.put(BUFFER_PROPERTY_NAME, new HashMap<String, Map>());
    }
    Map<String, Collection<Cache.Entry<?, ?>>> buffer = (Map<String, Collection<Cache.Entry<?, ?>>>) properties.get(BUFFER_PROPERTY_NAME);
    if (caches.add(cacheName)) {
        Collection<Cache.Entry<?, ?>> cacheBuffer = new ArrayList<>();
        buffer.put(cacheName, cacheBuffer);
        return cacheBuffer;
    } else {
        return buffer.get(cacheName);
    }
}
 
開發者ID:epam,項目名稱:Lagerta,代碼行數:22,代碼來源:DataCapturerBus.java

示例15: sessionEnd

import javax.cache.Cache; //導入依賴的package包/類
/**
 * {@inheritDoc}
 */
@Override
public void sessionEnd(boolean commit) throws CacheWriterException {
    Transaction transaction = session.transaction();
    if (transaction == null) {
        return;
    }
    Map<Object, Object> properties = session.properties();
    if (!commit) {
        Map bigBuffer = (Map) properties.get(BUFFER_PROPERTY_NAME);
        if (bigBuffer != null) {
            bigBuffer.remove(cacheName);
        }
    }
    Set<String> caches = (Set<String>) properties.get(CACHES_PROPERTY_NAME);
    if (caches != null && caches.remove(cacheName) && caches.isEmpty()) {
        Map<String, Collection<Cache.Entry<?, ?>>> buffer =
                (Map<String, Collection<Cache.Entry<?, ?>>>) properties.get(BUFFER_PROPERTY_NAME);
        notifyListeners(nextTransactionId(), buffer);
    }
}
 
開發者ID:epam,項目名稱:Lagerta,代碼行數:24,代碼來源:DataCapturerBus.java


注:本文中的javax.cache.Cache類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。