本文整理汇总了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;
}
示例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;
}
}
}
示例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();
}
示例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);
});
}
示例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();
}
示例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();
}
示例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
);
}
示例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())));
}
}
示例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);
}
示例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());
}
示例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);
}
示例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;
});
}
示例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);
}
}
示例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);
}
}