Search in sources :

Example 1 with CacheKey

use of top.tangyh.basic.model.cache.CacheKey in project lamp-util by zuihou.

the class SuperCacheServiceImpl method delCache.

protected void delCache(T model) {
    Object id = getId(model);
    if (id != null) {
        CacheKey key = cacheKeyBuilder().key(id);
        cacheOps.del(key);
    }
}
Also used : CacheKey(top.tangyh.basic.model.cache.CacheKey)

Example 2 with CacheKey

use of top.tangyh.basic.model.cache.CacheKey in project lamp-util by zuihou.

the class SuperCacheServiceImpl method findByIds.

@Override
@Transactional(readOnly = true)
public List<T> findByIds(@NonNull Collection<? extends Serializable> ids, Function<Collection<? extends Serializable>, Collection<T>> loader) {
    if (ids.isEmpty()) {
        return Collections.emptyList();
    }
    // 拼接keys
    List<CacheKey> keys = ids.stream().map(cacheKeyBuilder()::key).collect(Collectors.toList());
    // 切割
    List<List<CacheKey>> partitionKeys = Lists.partition(keys, MAX_BATCH_KEY_SIZE);
    // 用切割后的 partitionKeys 分批去缓存查, 返回的是缓存中存在的数据
    List<T> valueList = partitionKeys.stream().map(ks -> (List<T>) cacheOps.find(ks)).flatMap(Collection::stream).collect(Collectors.toList());
    // 所有的key
    List<Serializable> keysList = Lists.newArrayList(ids);
    // 缓存不存在的key
    Set<Serializable> missedKeys = Sets.newLinkedHashSet();
    List<T> allList = new ArrayList<>();
    for (int i = 0; i < valueList.size(); i++) {
        T v = valueList.get(i);
        Serializable k = keysList.get(i);
        if (v == null) {
            missedKeys.add(k);
        } else {
            allList.add(v);
        }
    }
    // 加载miss 的数据,并设置到缓存
    if (CollUtil.isNotEmpty(missedKeys)) {
        if (loader == null) {
            loader = this::listByIds;
        }
        Collection<T> missList = loader.apply(missedKeys);
        missList.forEach(this::setCache);
        allList.addAll(missList);
    }
    return allList;
}
Also used : Serializable(java.io.Serializable) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) CacheKey(top.tangyh.basic.model.cache.CacheKey) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with CacheKey

use of top.tangyh.basic.model.cache.CacheKey in project lamp-util by zuihou.

the class SuperCacheServiceImpl method setCache.

protected void setCache(T model) {
    Object id = getId(model);
    if (id != null) {
        CacheKey key = cacheKeyBuilder().key(id);
        cacheOps.set(key, model);
    }
}
Also used : CacheKey(top.tangyh.basic.model.cache.CacheKey)

Aggregations

CacheKey (top.tangyh.basic.model.cache.CacheKey)3 Serializable (java.io.Serializable)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Transactional (org.springframework.transaction.annotation.Transactional)1