|
@@ -10,6 +10,9 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.beans.factory.annotation.Qualifier;
|
|
|
import org.springframework.data.redis.core.RedisTemplate;
|
|
|
|
|
|
+import java.util.Iterator;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
import java.util.concurrent.TimeUnit;
|
|
|
import java.util.function.Function;
|
|
|
|
|
@@ -62,6 +65,11 @@ public abstract class AbstractFeatureService<K, V> {
|
|
|
public V load(K key) {
|
|
|
return AbstractFeatureService.this.load(key);
|
|
|
}
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public Map<K, V> loadAll(Iterable<? extends K> keys) {
|
|
|
+ return AbstractFeatureService.this.loadAll(keys);
|
|
|
+ }
|
|
|
});
|
|
|
}
|
|
|
|
|
@@ -87,7 +95,7 @@ public abstract class AbstractFeatureService<K, V> {
|
|
|
}
|
|
|
|
|
|
private V getFromCache(K key) {
|
|
|
- String redisKey = keyFunc.apply(key);
|
|
|
+ String redisKey = cacheKey(key);
|
|
|
String value = redisTemplate.opsForValue().get(redisKey);
|
|
|
return JSONUtils.fromJson(value, typeToken, null);
|
|
|
}
|
|
@@ -110,6 +118,45 @@ public abstract class AbstractFeatureService<K, V> {
|
|
|
redisTemplate.opsForValue().set(cacheKey, cacheValue, expire, TimeUnit.SECONDS);
|
|
|
}
|
|
|
|
|
|
+ private Map<K, V> loadAll(Iterable<? extends K> keyIte) {
|
|
|
+
|
|
|
+ Map<K,V> featureMap = getFromCache(keyIte);
|
|
|
+ if (feature == null) {
|
|
|
+ feature = getFromSource(keyIte);
|
|
|
+ // TODO 可异步
|
|
|
+ saveToCache();
|
|
|
+ }
|
|
|
+ return feature;
|
|
|
+ }
|
|
|
+
|
|
|
+ private V getFromCache(Iterable<? extends K> keyIte) {
|
|
|
+
|
|
|
+ Iterator<? extends K> ite = keyIte.iterator();
|
|
|
+ while (ite.hasNext()) {
|
|
|
+ keys.add(ite.next());
|
|
|
+ }
|
|
|
+ String redisKey = cacheKey(key);
|
|
|
+ String value = redisTemplate.opsForValue().get(redisKey);
|
|
|
+ return JSONUtils.fromJson(value, typeToken, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ private V getFromSource(Iterable<? extends K> keyIte) {
|
|
|
+ String sourceKey = cacheKey(key);
|
|
|
+ String value = tairTemplate.opsForValue().get(sourceKey);
|
|
|
+ return JSONUtils.fromJson(value, typeToken, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void saveToCache(Map<K, V> map) {
|
|
|
+ String cacheKey = cacheKey(key);
|
|
|
+ String cacheValue = value == null
|
|
|
+ ? emptyData
|
|
|
+ : JSONUtils.toJson(value);
|
|
|
+ long expire = value == null
|
|
|
+ ? emptyDataExpire
|
|
|
+ : defaultExpire;
|
|
|
+ // TODO 评估过期时间
|
|
|
+ redisTemplate.opsForValue().set(cacheKey, cacheValue, expire, TimeUnit.SECONDS);
|
|
|
+ }
|
|
|
|
|
|
private String cacheKey(K key) {
|
|
|
return keyFunc.apply(key);
|
|
@@ -132,4 +179,11 @@ public abstract class AbstractFeatureService<K, V> {
|
|
|
redisTemplate.delete(cacheKey);
|
|
|
}
|
|
|
|
|
|
+ protected List<V> getAll(List<K> videoIds) {
|
|
|
+ try {
|
|
|
+ cache.getAll(videoIds);
|
|
|
+ } catch (Exception e) {
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|