index
int64
0
36.5k
proj_name
stringclasses
162 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
51
masked_class
stringlengths
68
9.82k
func_body
stringlengths
46
9.61k
len_func_body
int64
1
5.26k
len_input
int64
27
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
0
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjAopInterceptor.java
AspectjAopInterceptor
checkAndProceed
class AspectjAopInterceptor { private final CacheHandler cacheHandler; public AspectjAopInterceptor(CacheHandler cacheHandler) { this.cacheHandler = cacheHandler; } public Object checkAndProceed(ProceedingJoinPoint pjp) throws Throwable {<FILL_FUNCTION_BODY>} public void checkAndDeleteCache(JoinPoint jp, Object retVal) throws Throwable { Signature signature = jp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(CacheDelete.class)) { CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class); this.deleteCache(jp, cacheDelete, retVal); } } public Object checkAndDeleteCacheTransactional(ProceedingJoinPoint pjp) throws Throwable { Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(CacheDeleteTransactional.class)) { CacheDeleteTransactional cache = method.getAnnotation(CacheDeleteTransactional.class);// method.getAnnotationsByType(Cache.class)[0]; return this.deleteCacheTransactional(pjp, cache); } try { return pjp.proceed(); } catch (Throwable e) { throw e; } } public Object proceed(ProceedingJoinPoint aopProxyChain, Cache cache) throws Throwable { return cacheHandler.proceed(new AspectjCacheAopProxyChain(aopProxyChain), cache); } public void deleteCache(JoinPoint aopProxyChain, CacheDelete cacheDelete, Object retVal) throws Throwable { cacheHandler.deleteCache(new AspectjDeleteCacheAopProxyChain(aopProxyChain), cacheDelete, retVal); } public Object deleteCacheTransactional(ProceedingJoinPoint aopProxyChain, CacheDeleteTransactional cacheDeleteTransactional) throws Throwable { return cacheHandler.proceedDeleteCacheTransactional( new AspectjDeleteCacheTransactionalAopProxyChain(aopProxyChain), cacheDeleteTransactional); } public CacheHandler getCacheHandler() { return cacheHandler; } }
Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(Cache.class)) { Cache cache = method.getAnnotation(Cache.class);// method.getAnnotationsByType(Cache.class)[0]; return this.proceed(pjp, cache); } try { return pjp.proceed(); } catch (Throwable e) { throw e; }
142
591
134
725
1
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjCacheAopProxyChain.java
AspectjCacheAopProxyChain
getMethod
class AspectjCacheAopProxyChain implements CacheAopProxyChain { private final ProceedingJoinPoint jp; private Method method; public AspectjCacheAopProxyChain(ProceedingJoinPoint jp) { this.jp = jp; } @Override public Object[] getArgs() { return jp.getArgs(); } @Override public Object getTarget() { return jp.getTarget(); } @Override public Method getMethod() {<FILL_FUNCTION_BODY>} @Override public Object doProxyChain(Object[] arguments) throws Throwable { return jp.proceed(arguments); } }
if (null == method) { Signature signature = jp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; this.method = methodSignature.getMethod(); } return method;
79
188
57
245
2
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/CacheUtil.java
CacheUtil
isEmpty
class CacheUtil { private static final String SPLIT_STR = "_"; @SuppressWarnings("rawtypes") public static boolean isEmpty(Object obj) {<FILL_FUNCTION_BODY>} /** * 生成字符串的HashCode * * @param buf * @return int hashCode */ private static int getHashCode(String buf) { int hash = 5381; int len = buf.length(); while (len-- > 0) { hash = ((hash << 5) + hash) + buf.charAt(len); } return hash; } /** * 将Object 对象转换为唯一的Hash字符串 * * @param obj Object * @return Hash字符串 */ public static String getUniqueHashStr(Object obj) { return getMiscHashCode(BeanUtil.toString(obj)); } /** * 通过混合Hash算法,将长字符串转为短字符串(字符串长度小于等于20时,不做处理) * * @param str String * @return Hash字符串 */ public static String getMiscHashCode(String str) { if (null == str || str.length() == 0) { return ""; } int originSize = 20; if (str.length() <= originSize) { return str; } StringBuilder tmp = new StringBuilder(); tmp.append(str.hashCode()).append(SPLIT_STR).append(getHashCode(str)); int mid = str.length() / 2; String str1 = str.substring(0, mid); String str2 = str.substring(mid); tmp.append(SPLIT_STR).append(str1.hashCode()); tmp.append(SPLIT_STR).append(str2.hashCode()); return tmp.toString(); } /** * 生成缓存Key * * @param className 类名称 * @param method 方法名称 * @param arguments 参数 * @return CacheKey 缓存Key */ public static String getDefaultCacheKey(String className, String method, Object[] arguments) { StringBuilder sb = new StringBuilder(); sb.append(getDefaultCacheKeyPrefix(className, method, arguments)); if (null != arguments && arguments.length > 0) { sb.append(getUniqueHashStr(arguments)); } return sb.toString(); } /** * 生成缓存Key的前缀 * * @param className 类名称 * @param method 方法名称 * @param arguments 参数 * @return CacheKey 缓存Key */ public static String getDefaultCacheKeyPrefix(String className, String method, Object[] arguments) { StringBuilder sb = new StringBuilder(); sb.append(className); if (null != method && method.length() > 0) { sb.append(".").append(method); } return sb.toString(); } }
if (null == obj) { return true; } if (obj instanceof String) { return ((String) obj).length() == 0; } Class cl = obj.getClass(); if (cl.isArray()) { int len = Array.getLength(obj); return len == 0; } if (obj instanceof Collection) { Collection tempCol = (Collection) obj; return tempCol.isEmpty(); } if (obj instanceof Map) { Map tempMap = (Map) obj; return tempMap.isEmpty(); } return false;
240
807
154
961
3
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/comparator/AutoLoadOldestComparator.java
AutoLoadOldestComparator
compare
class AutoLoadOldestComparator implements Comparator<AutoLoadTO> { @Override public int compare(AutoLoadTO autoLoadTO1, AutoLoadTO autoLoadTO2) {<FILL_FUNCTION_BODY>} }
if (autoLoadTO1 == null && autoLoadTO2 != null) { return 1; } else if (autoLoadTO1 != null && autoLoadTO2 == null) { return -1; } else if (autoLoadTO1 == null && autoLoadTO2 == null) { return 0; } long now = System.currentTimeMillis(); long dif1 = now - autoLoadTO1.getLastLoadTime() - autoLoadTO1.getCache().expire() * 1000; long dif2 = now - autoLoadTO2.getLastLoadTime() - autoLoadTO2.getCache().expire() * 1000; if (dif1 > dif2) { return -1; } else if (dif1 < dif2) { return 1; } else { if (autoLoadTO1.getAverageUseTime() > autoLoadTO2.getAverageUseTime()) { return -1; } else if (autoLoadTO1.getAverageUseTime() < autoLoadTO2.getAverageUseTime()) { return 1; } } return 0;
308
62
298
360
4
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/comparator/AutoLoadRequestTimesComparator.java
AutoLoadRequestTimesComparator
compare
class AutoLoadRequestTimesComparator implements Comparator<AutoLoadTO> { @Override public int compare(AutoLoadTO autoLoadTO1, AutoLoadTO autoLoadTO2) {<FILL_FUNCTION_BODY>} }
if (autoLoadTO1 == null && autoLoadTO2 != null) { return 1; } else if (autoLoadTO1 != null && autoLoadTO2 == null) { return -1; } else if (autoLoadTO1 == null && autoLoadTO2 == null) { return 0; } if (autoLoadTO1.getRequestTimes() > autoLoadTO2.getRequestTimes()) { return -1; } else if (autoLoadTO1.getRequestTimes() < autoLoadTO2.getRequestTimes()) { return 1; } return 0;
173
62
158
220
5
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/reflect/generics/ParameterizedTypeImpl.java
ParameterizedTypeImpl
toString
class ParameterizedTypeImpl implements ParameterizedType { private Type[] actualTypeArguments; private Class<?> rawType; private Type ownerType; private ParameterizedTypeImpl(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) { this.actualTypeArguments = paramArrayOfType; this.rawType = paramClass; if (paramType != null) { this.ownerType = paramType; } else { this.ownerType = paramClass.getDeclaringClass(); } validateConstructorArguments(); } private void validateConstructorArguments() { @SuppressWarnings("rawtypes") TypeVariable[] arrayOfTypeVariable = this.rawType.getTypeParameters(); if (arrayOfTypeVariable.length != this.actualTypeArguments.length) { throw new MalformedParameterizedTypeException(); } // for(int i=0; i < this.actualTypeArguments.length; i++); } public static ParameterizedTypeImpl make(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) { return new ParameterizedTypeImpl(paramClass, paramArrayOfType, paramType); } @Override public Type[] getActualTypeArguments() { return (Type[]) this.actualTypeArguments.clone(); } @Override public Class<?> getRawType() { return this.rawType; } @Override public Type getOwnerType() { return this.ownerType; } @Override public boolean equals(Object paramObject) { if ((paramObject instanceof ParameterizedType)) { ParameterizedType localParameterizedType = (ParameterizedType) paramObject; if (this == localParameterizedType) { return true; } Type localType1 = localParameterizedType.getOwnerType(); Type localType2 = localParameterizedType.getRawType(); return (this.ownerType == null ? localType1 == null : this.ownerType.equals(localType1)) && (this.rawType == null ? localType2 == null : this.rawType.equals(localType2)) && (Arrays.equals(this.actualTypeArguments, localParameterizedType.getActualTypeArguments())); } return false; } @Override public int hashCode() { return Arrays.hashCode(this.actualTypeArguments) ^ (this.ownerType == null ? 0 : this.ownerType.hashCode()) ^ (this.rawType == null ? 0 : this.rawType.hashCode()); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder localStringBuilder = new StringBuilder(); if (this.ownerType != null) { if ((this.ownerType instanceof Class<?>)) localStringBuilder.append(((Class<?>) this.ownerType).getName()); else { localStringBuilder.append(this.ownerType.toString()); } localStringBuilder.append("."); if ((this.ownerType instanceof ParameterizedTypeImpl)) { localStringBuilder.append(this.rawType.getName() .replace(((ParameterizedTypeImpl) this.ownerType).rawType.getName() + "$", "")); } else { localStringBuilder.append(this.rawType.getName()); } } else { localStringBuilder.append(this.rawType.getName()); } if ((this.actualTypeArguments != null) && (this.actualTypeArguments.length > 0)) { localStringBuilder.append("<"); int i = 1; for (Type localType : this.actualTypeArguments) { if (i == 0) { localStringBuilder.append(", "); } if ((localType instanceof Class<?>)) { localStringBuilder.append(((Class<?>) localType).getName()); } else { // if(null!=localType){ localStringBuilder.append(localType.toString()); // } } i = 0; } localStringBuilder.append(">"); } return localStringBuilder.toString();
559
688
381
1,069
9
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/AutoLoadTO.java
AutoLoadTO
equals
class AutoLoadTO implements Serializable { private static final long serialVersionUID = 1L; private final CacheAopProxyChain joinPoint; private final Object[] args; /** * 缓存注解 */ private final Cache cache; /** * 缓存时长 */ private int expire; /** * 缓存Key */ private final CacheKeyTO cacheKey; /** * 上次从DAO加载数据时间 */ private long lastLoadTime = 0L; /** * 上次请求数据时间 */ private long lastRequestTime = 0L; /** * 第一次请求数据时间 */ private long firstRequestTime = 0L; /** * 请求数据次数 */ private long requestTimes = 0L; private volatile boolean loading = false; /** * 加载次数 */ private long loadCnt = 0L; /** * 从DAO中加载数据,使用时间的总和 */ private long useTotalTime = 0L; public AutoLoadTO(CacheKeyTO cacheKey, CacheAopProxyChain joinPoint, Object args[], Cache cache, int expire) { this.cacheKey = cacheKey; this.joinPoint = joinPoint; this.args = args; this.cache = cache; this.expire = expire; } public CacheAopProxyChain getJoinPoint() { return joinPoint; } public long getLastRequestTime() { return lastRequestTime; } public AutoLoadTO setLastRequestTime(long lastRequestTime) { synchronized (this) { this.lastRequestTime = lastRequestTime; if (firstRequestTime == 0) { firstRequestTime = lastRequestTime; } requestTimes++; } return this; } /** * @param firstRequestTime System.currentTimeMillis() */ public void setFirstRequestTime(long firstRequestTime) { this.firstRequestTime = firstRequestTime; } public long getFirstRequestTime() { return firstRequestTime; } public long getRequestTimes() { return requestTimes; } public Cache getCache() { return cache; } public long getLastLoadTime() { return lastLoadTime; } /** * @param lastLoadTime last load time * @return this */ public AutoLoadTO setLastLoadTime(long lastLoadTime) { this.lastLoadTime = lastLoadTime; return this; } public CacheKeyTO getCacheKey() { return cacheKey; } public boolean isLoading() { return loading; } /** * @param loading 是否正在加载 * @return this */ public AutoLoadTO setLoading(boolean loading) { this.loading = loading; return this; } public Object[] getArgs() { return args; } public long getLoadCnt() { return loadCnt; } public long getUseTotalTime() { return useTotalTime; } /** * 记录用时 * * @param useTime 用时 * @return this */ public AutoLoadTO addUseTotalTime(long useTime) { synchronized (this) { this.loadCnt++; this.useTotalTime += useTime; } return this; } /** * 平均耗时 * * @return long 平均耗时 */ public long getAverageUseTime() { if (loadCnt == 0) { return 0; } return this.useTotalTime / this.loadCnt; } public int getExpire() { return expire; } /** * @param expire expire * @return this */ public AutoLoadTO setExpire(int expire) { this.expire = expire; return this; } public void flushRequestTime(CacheWrapper<Object> cacheWrapper) { // 同步最后加载时间 this.setLastRequestTime(System.currentTimeMillis()) // 同步加载时间 .setLastLoadTime(cacheWrapper.getLastLoadTime()) // 同步过期时间 .setExpire(cacheWrapper.getExpire()); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = Objects.hash(joinPoint, cache, expire, cacheKey, lastLoadTime, lastRequestTime, firstRequestTime, requestTimes, loading, loadCnt, useTotalTime); result = 31 * result + Arrays.hashCode(args); return result; } @Override public String toString() { return "AutoLoadTO{" + "joinPoint=" + joinPoint + ", args=" + Arrays.toString(args) + ", cache=" + cache + ", expire=" + expire + ", cacheKey=" + cacheKey + ", lastLoadTime=" + lastLoadTime + ", lastRequestTime=" + lastRequestTime + ", firstRequestTime=" + firstRequestTime + ", requestTimes=" + requestTimes + ", loading=" + loading + ", loadCnt=" + loadCnt + ", useTotalTime=" + useTotalTime + '}'; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AutoLoadTO that = (AutoLoadTO) o; return expire == that.expire && lastLoadTime == that.lastLoadTime && lastRequestTime == that.lastRequestTime && firstRequestTime == that.firstRequestTime && requestTimes == that.requestTimes && loading == that.loading && loadCnt == that.loadCnt && useTotalTime == that.useTotalTime && Objects.equals(joinPoint, that.joinPoint) && Arrays.equals(args, that.args) && Objects.equals(cache, that.cache) && Objects.equals(cacheKey, that.cacheKey);
263
1,461
197
1,658
10
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/CacheKeyTO.java
CacheKeyTO
equals
class CacheKeyTO implements Serializable { private static final long serialVersionUID = 7229320497442357252L; private final String namespace; private final String key;// 缓存Key private final String hfield;// 设置哈希表中的字段,如果设置此项,则用哈希表进行存储 public CacheKeyTO(String namespace, String key, String hfield) { this.namespace = namespace; this.key = key; this.hfield = hfield; } public String getCacheKey() { if (null != this.namespace && this.namespace.length() > 0) { return new StringBuilder(this.namespace).append(":").append(this.key).toString(); } return this.key; } public String getLockKey() { StringBuilder key = new StringBuilder(getCacheKey()); if (null != hfield && hfield.length() > 0) { key.append(":").append(hfield); } key.append(":lock"); return key.toString(); } public String getNamespace() { return namespace; } public String getHfield() { return hfield; } public String getKey() { return key; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(namespace, key, hfield); } @Override public String toString() { return "CacheKeyTO{" + "namespace='" + namespace + '\'' + ", key='" + key + '\'' + ", hfield='" + hfield + '\'' + '}'; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheKeyTO that = (CacheKeyTO) o; return Objects.equals(namespace, that.namespace) && Objects.equals(key, that.key) && Objects.equals(hfield, that.hfield);
93
470
93
563
11
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/CacheWrapper.java
CacheWrapper
isExpired
class CacheWrapper<T> implements Serializable, Cloneable { private static final long serialVersionUID = 1L; /** * 缓存数据 */ private T cacheObject; /** * 最后加载时间 */ private long lastLoadTime; /** * 缓存时长 */ private int expire; public CacheWrapper() { } public CacheWrapper(T cacheObject, int expire) { this.cacheObject = cacheObject; this.lastLoadTime = System.currentTimeMillis(); this.expire = expire; } public CacheWrapper(T cacheObject, int expire, long lastLoadTime) { this.cacheObject = cacheObject; this.lastLoadTime = lastLoadTime; this.expire = expire; } /** * 判断缓存是否已经过期 * * @return boolean */ public boolean isExpired() {<FILL_FUNCTION_BODY>} public int getExpire() { return expire; } public void setCacheObject(T cacheObject) { this.cacheObject = cacheObject; } public long getLastLoadTime() { return lastLoadTime; } public T getCacheObject() { return cacheObject; } public void setLastLoadTime(long lastLoadTime) { this.lastLoadTime = lastLoadTime; } public void setExpire(int expire) { this.expire = expire; } @Override public Object clone() throws CloneNotSupportedException { @SuppressWarnings("unchecked") CacheWrapper<T> tmp = (CacheWrapper<T>) super.clone(); tmp.setCacheObject(this.cacheObject); return tmp; } }
if (expire > 0) { return (System.currentTimeMillis() - lastLoadTime) > expire * 1000; } return false;
53
485
47
532
12
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/ProcessingTO.java
ProcessingTO
equals
class ProcessingTO { private volatile long startTime; private volatile CacheWrapper<Object> cache; private volatile boolean firstFinished = false; private volatile Throwable error; public ProcessingTO() { startTime = System.currentTimeMillis(); } public CacheWrapper<Object> getCache() { return cache; } public void setCache(CacheWrapper<Object> cache) { this.cache = cache; } public void setFirstFinished(boolean firstFinished) { this.firstFinished = firstFinished; } public boolean isFirstFinished() { return this.firstFinished; } public long getStartTime() { return startTime; } public void setError(Throwable error) { this.error = error; } public Throwable getError() { return this.error; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(startTime, cache, firstFinished, error); } @Override public String toString() { return "ProcessingTO{" + "startTime=" + startTime + ", cache=" + cache + ", firstFinished=" + firstFinished + ", error=" + error + '}'; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProcessingTO that = (ProcessingTO) o; return startTime == that.startTime && firstFinished == that.firstFinished && Objects.equals(cache, that.cache) && Objects.equals(error, that.error);
113
378
99
477
13
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/BeanUtil.java
BeanUtil
toString
class BeanUtil { @SuppressWarnings("rawtypes") private static final ConcurrentHashMap<Class, Field[]> FIELDS_CAHCE = new ConcurrentHashMap<Class, Field[]>(); /** * 是否为基础数据类型 * * @param obj Object * @return boolean true or false */ public static boolean isPrimitive(Object obj) { boolean rv = obj.getClass().isPrimitive() || obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Byte || obj instanceof Character || obj instanceof Boolean || obj instanceof Short || obj instanceof Float || obj instanceof Double || obj instanceof BigDecimal || obj instanceof BigInteger; return rv; } /** * 把Bean转换为字符串 * * @param obj Object * @return String String */ @SuppressWarnings("rawtypes") public static String toString(Object obj) {<FILL_FUNCTION_BODY>} }
if (obj == null) { return "null"; } Class cl = obj.getClass(); if (isPrimitive(obj)) { return String.valueOf(obj); } else if (obj instanceof Enum) { return ((Enum) obj).name(); } else if (obj instanceof Date) { return String.valueOf(((Date) obj).getTime()); } else if (obj instanceof Calendar) { return String.valueOf(((Calendar) obj).getTime().getTime()); } else if (cl.isArray()) { String r = "["; int len = Array.getLength(obj); for (int i = 0; i < len; i++) { if (i > 0) { r += ","; } Object val = Array.get(obj, i); r += toString(val); } return r + "]"; } else if (obj instanceof Collection) { Collection tempCol = (Collection) obj; Iterator it = tempCol.iterator(); String r = "["; for (int i = 0; it.hasNext(); i++) { if (i > 0) { r += ","; } Object val = it.next(); r += toString(val); } return r + "]"; } else if (obj instanceof Map) { Map tempMap = (Map) obj; String r = "{"; Iterator it = tempMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Entry) it.next(); Object key = entry.getKey(); r += toString(key); r += "="; Object val = entry.getValue(); r += toString(val); if (it.hasNext()) { r += ","; } } return r + "}"; } else if (obj instanceof Class) { Class tmpCls = (Class) obj; return tmpCls.getName(); } String r = cl.getName(); do { Field[] fields = FIELDS_CAHCE.get(cl); if (null == fields) { fields = cl.getDeclaredFields(); if (null != fields) { AccessibleObject.setAccessible(fields, true); } FIELDS_CAHCE.put(cl, fields); } if (null == fields || fields.length == 0) { cl = cl.getSuperclass(); continue; } r += "["; // get the names and values of all fields for (Field f : fields) { if (Modifier.isStatic(f.getModifiers())) { continue; } if (f.isSynthetic() || f.getName().indexOf("this$") != -1) { continue; } r += f.getName() + "="; try { Object val = f.get(obj); r += toString(val); } catch (Exception e) { e.printStackTrace(); } r += ","; } String comma = ","; if (r.endsWith(comma)) { r = r.substring(0, r.length() - 1); } r += "]"; cl = cl.getSuperclass(); } while (cl != null); return r;
1,526
256
871
1,127
14
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/StringUtil.java
StringUtil
containsText
class StringUtil { /** * Check whether the given {@code CharSequence} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code CharSequence} is not {@code null}, its length is greater than * 0, and it contains at least one non-whitespace character. * <p><pre class="code"> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * @param str the {@code CharSequence} to check (may be {@code null}) * @return {@code true} if the {@code CharSequence} is not {@code null}, * its length is greater than 0, and it does not contain whitespace only * @see Character#isWhitespace */ public static boolean hasText(CharSequence str) { return (str != null && str.length() > 0 && containsText(str)); } /** * Check whether the given {@code String} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code String} is not {@code null}, its length is greater than 0, * and it contains at least one non-whitespace character. * @param str the {@code String} to check (may be {@code null}) * @return {@code true} if the {@code String} is not {@code null}, its * length is greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) */ public static boolean hasText(String str) { return (str != null && !str.isEmpty() && containsText(str)); } private static boolean containsText(CharSequence str) {<FILL_FUNCTION_BODY>} }
int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false;
93
511
66
577
15
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/AutoLoadHandler.java
AutoLoadRunnable
loadCache
class AutoLoadRunnable implements Runnable { @Override public void run() { while (running) { try { AutoLoadTO tmpTO = autoLoadQueue.take(); if (null != tmpTO) { loadCache(tmpTO); Thread.sleep(config.getAutoLoadPeriod()); } } catch (InterruptedException e) { log.error(e.getMessage(), e); } } } private void loadCache(AutoLoadTO autoLoadTO) {<FILL_FUNCTION_BODY>} }
if (null == autoLoadTO) { return; } long now = System.currentTimeMillis(); if (autoLoadTO.getLastRequestTime() <= 0 || autoLoadTO.getLastLoadTime() <= 0) { return; } Cache cache = autoLoadTO.getCache(); long requestTimeout = cache.requestTimeout(); boolean alwaysCache = cache.alwaysCache(); // 如果超过一定时间没有请求数据,则从队列中删除 if (!alwaysCache && requestTimeout > 0 && (now - autoLoadTO.getLastRequestTime()) >= requestTimeout * ONE_THOUSAND_MS) { autoLoadMap.remove(autoLoadTO.getCacheKey()); return; } // 如果效率比较高的请求,就没必要使用自动加载了。 if (!alwaysCache && autoLoadTO.getLoadCnt() > 100 && autoLoadTO.getAverageUseTime() < config.getLoadUseTimeForAutoLoad1()) { autoLoadMap.remove(autoLoadTO.getCacheKey()); return; } // 对于使用频率很低的数据,也可以考虑不用自动加载 long difFirstRequestTime = now - autoLoadTO.getFirstRequestTime(); long oneHourSecs = 3600000L; // 如果是耗时不大,且使用率比较低的数据,没有必要使用自动加载。 if (!alwaysCache && difFirstRequestTime > oneHourSecs && autoLoadTO.getAverageUseTime() < config.getLoadUseTimeForAutoLoad2() && (autoLoadTO.getRequestTimes() / (difFirstRequestTime / oneHourSecs)) < 60) { autoLoadMap.remove(autoLoadTO.getCacheKey()); return; } if (autoLoadTO.isLoading()) { return; } int expire = autoLoadTO.getExpire(); // 如果过期时间太小了,就不允许自动加载,避免加载过于频繁,影响系统稳定性 if (!alwaysCache && expire < AUTO_LOAD_MIN_EXPIRE) { return; } // 计算超时时间 int alarmTime = autoLoadTO.getCache().alarmTime(); long timeout; if (alarmTime > 0 && alarmTime < expire) { timeout = expire - alarmTime; } else { if (expire >= 600) { timeout = expire - 120; } else { timeout = expire - 60; } } int rand = ThreadLocalRandom.current().nextInt(10); timeout = (timeout + (rand % 2 == 0 ? rand : -rand)) * ONE_THOUSAND_MS; if ((now - autoLoadTO.getLastLoadTime()) < timeout) { return; } CacheWrapper<Object> result = null; if (config.isCheckFromCacheBeforeLoad()) { try { Method method = autoLoadTO.getJoinPoint().getMethod(); // Type returnType=method.getGenericReturnType(); result = cacheHandler.get(autoLoadTO.getCacheKey(), method); } catch (Exception ex) { log.error(ex.getMessage(), ex); } // 如果已经被别的服务器更新了,则不需要再次更新 if (null != result) { autoLoadTO.setExpire(result.getExpire()); if (result.getLastLoadTime() > autoLoadTO.getLastLoadTime() && (now - result.getLastLoadTime()) < timeout) { autoLoadTO.setLastLoadTime(result.getLastLoadTime()); return; } } } CacheAopProxyChain pjp = autoLoadTO.getJoinPoint(); CacheKeyTO cacheKey = autoLoadTO.getCacheKey(); DataLoader dataLoader; if (config.isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); dataLoader = factory.getDataLoader(); } else { dataLoader = new DataLoader(); } CacheWrapper<Object> newCacheWrapper = null; boolean isFirst = false; long loadDataUseTime = 0L; try { newCacheWrapper = dataLoader.init(pjp, autoLoadTO, cacheKey, cache, cacheHandler).loadData() .getCacheWrapper(); loadDataUseTime = dataLoader.getLoadDataUseTime(); } catch (Throwable e) { log.error(e.getMessage(), e); } finally { // dataLoader 的数据必须在放回对象池之前获取 isFirst = dataLoader.isFirst(); if (config.isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); factory.returnObject(dataLoader); } } if (isFirst) { // 如果数据加载失败,则把旧数据进行续租 if (null == newCacheWrapper && null != result) { int newExpire = !alwaysCache ? AUTO_LOAD_MIN_EXPIRE + 60 : cache.expire(); newCacheWrapper = new CacheWrapper<Object>(result.getCacheObject(), newExpire); } writeCacheAndSetLoadTime(cache, pjp, cacheKey, newCacheWrapper, loadDataUseTime, autoLoadTO); }
1,857
146
1,346
1,492
17
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/CacheHelper.java
CacheHelper
initDeleteCacheKeysSet
class CacheHelper { private static final ThreadLocal<CacheOpType> OP_TYPE = new ThreadLocal<CacheOpType>(); private static final ThreadLocal<Set<CacheKeyTO>> DELETE_CACHE_KEYS = new ThreadLocal<Set<CacheKeyTO>>(); /** * 获取CacheOpType * * @return ThreadLocal中设置的CacheOpType */ public static CacheOpType getCacheOpType() { return OP_TYPE.get(); } /** * 设置CacheOpType * * @param opType CacheOpType */ public static void setCacheOpType(CacheOpType opType) { OP_TYPE.set(opType); } /** * 移除CacheOpType */ public static void clearCacheOpType() { OP_TYPE.remove(); } public static void initDeleteCacheKeysSet() {<FILL_FUNCTION_BODY>} public static Set<CacheKeyTO> getDeleteCacheKeysSet() { return DELETE_CACHE_KEYS.get(); } public static void addDeleteCacheKey(CacheKeyTO key) { Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get(); if (null != set) { set.add(key); } } public static boolean isOnTransactional() { Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get(); return null != set; } public static void clearDeleteCacheKeysSet() { DELETE_CACHE_KEYS.remove(); } }
Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get(); if (null == set) { set = new HashSet<CacheKeyTO>(); DELETE_CACHE_KEYS.set(set); }
63
421
66
487
18
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/ComboCacheManager.java
ComboCacheManager
mget
class ComboCacheManager implements ICacheManager { /** * 表达式解析器 */ private final AbstractScriptParser scriptParser; /** * 本地缓存实现 */ private ICacheManager localCache; /** * 远程缓存实现 */ private ICacheManager remoteCache; private static final Logger log = LoggerFactory.getLogger(ComboCacheManager.class); public ComboCacheManager(ICacheManager localCache, ICacheManager remoteCache, AbstractScriptParser scriptParser) { this.localCache = localCache; this.remoteCache = remoteCache; this.scriptParser = scriptParser; } @Override public void setCache(CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) throws CacheCenterConnectionException { if (method.isAnnotationPresent(LocalCache.class)) { LocalCache lCache = method.getAnnotation(LocalCache.class); setLocalCache(lCache, cacheKey, result, method); // 只本地缓存 if (lCache.localOnly()) { return; } } remoteCache.setCache(cacheKey, result, method); } @Override public void mset(Method method, Collection<MSetParam> params) throws CacheCenterConnectionException { if (method.isAnnotationPresent(LocalCache.class)) { LocalCache lCache = method.getAnnotation(LocalCache.class); for (MSetParam param : params) { if (param == null) { continue; } setLocalCache(lCache, param.getCacheKey(), param.getResult(), method); } // 只本地缓存 if (lCache.localOnly()) { return; } } remoteCache.mset(method, params); } private void setLocalCache(LocalCache lCache, CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) { try { LocalCacheWrapper<Object> localResult = new LocalCacheWrapper<Object>(); localResult.setLastLoadTime(System.currentTimeMillis()); int expire = scriptParser.getRealExpire(lCache.expire(), lCache.expireExpression(), null, result.getCacheObject()); localResult.setExpire(expire); localResult.setCacheObject(result.getCacheObject()); localResult.setRemoteExpire(result.getExpire()); localResult.setRemoteLastLoadTime(result.getLastLoadTime()); localCache.setCache(cacheKey, result, method); } catch (Exception e) { log.error(e.getMessage(), e); } } @Override public CacheWrapper<Object> get(CacheKeyTO key, Method method) throws CacheCenterConnectionException { LocalCache lCache = null; if (method.isAnnotationPresent(LocalCache.class)) { lCache = method.getAnnotation(LocalCache.class); } String threadName = Thread.currentThread().getName(); // 如果是自动加载线程,则只从远程缓存获取。 if (null != lCache && !threadName.startsWith(AutoLoadHandler.THREAD_NAME_PREFIX)) { CacheWrapper<Object> result = localCache.get(key, method); if (null != result) { if (result instanceof LocalCacheWrapper) { LocalCacheWrapper<Object> localResult = (LocalCacheWrapper<Object>) result; return new CacheWrapper<Object>(localResult.getCacheObject(), localResult.getRemoteExpire(), localResult.getRemoteLastLoadTime()); } else { return result; } } } CacheWrapper<Object> result = remoteCache.get(key, method); // 如果取到了则先放到本地缓存里 if (null != lCache && result != null) { setLocalCache(lCache, key, result, method); } return result; } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(final Method method, final Type returnType, final Set<CacheKeyTO> keys) throws CacheCenterConnectionException {<FILL_FUNCTION_BODY>} @Override public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException { localCache.delete(keys); remoteCache.delete(keys); } }
LocalCache lCache = null; if (method.isAnnotationPresent(LocalCache.class)) { lCache = method.getAnnotation(LocalCache.class); } else { return remoteCache.mget(method, returnType, keys); } String threadName = Thread.currentThread().getName(); Map<CacheKeyTO, CacheWrapper<Object>> all; Map<CacheKeyTO, CacheWrapper<Object>> remoteResults = null; if (!threadName.startsWith(AutoLoadHandler.THREAD_NAME_PREFIX)) { all = new HashMap<>(keys.size()); Map<CacheKeyTO, CacheWrapper<Object>> localResults = localCache.mget(method, returnType, keys); if (null != localResults && !localResults.isEmpty()) { Iterator<Map.Entry<CacheKeyTO, CacheWrapper<Object>>> iterator = localResults.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<CacheKeyTO, CacheWrapper<Object>> item = iterator.next(); CacheWrapper<Object> result = item.getValue(); if (result instanceof LocalCacheWrapper) { LocalCacheWrapper<Object> localResult = (LocalCacheWrapper<Object>) result; CacheWrapper<Object> result2 = new CacheWrapper<Object>(localResult.getCacheObject(), localResult.getRemoteExpire(), localResult.getRemoteLastLoadTime()); all.put(item.getKey(), result2); } else { all.put(item.getKey(), result); } } } if(all.size() < keys.size()) { Set<CacheKeyTO> unCachekeys = new HashSet<>(keys.size() - all.size()); for(CacheKeyTO key : keys) { if(!all.containsKey(key)) { unCachekeys.add(key); } } remoteResults = remoteCache.mget(method, returnType, keys); if(null != remoteResults && !remoteResults.isEmpty()) { all.putAll(remoteResults); } } } else { remoteResults = remoteCache.mget(method, returnType, keys); all = remoteResults; } if(null != remoteResults && !remoteResults.isEmpty()) { // 放到本地缓存里 Iterator<Map.Entry<CacheKeyTO, CacheWrapper<Object>>> iterator = remoteResults.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<CacheKeyTO, CacheWrapper<Object>> item = iterator.next(); setLocalCache(lCache, item.getKey(), item.getValue(), method); } } return all;
853
1,109
669
1,778
20
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/DataLoaderFactory.java
DataLoaderFactory
getInstance
class DataLoaderFactory extends BasePooledObjectFactory<DataLoader> { private static volatile DataLoaderFactory instance; private final GenericObjectPool<DataLoader> factory; private DataLoaderFactory() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(1024); config.setMaxIdle(50); config.setMinIdle(8); // 当Pool中没有对象时不等待,而是直接new个新的 config.setBlockWhenExhausted(false); AbandonedConfig abandonConfig = new AbandonedConfig(); abandonConfig.setRemoveAbandonedTimeout(300); abandonConfig.setRemoveAbandonedOnBorrow(true); abandonConfig.setRemoveAbandonedOnMaintenance(true); factory = new GenericObjectPool<DataLoader>(this, config, abandonConfig); } public static DataLoaderFactory getInstance() {<FILL_FUNCTION_BODY>} public DataLoader getDataLoader() { try { return factory.borrowObject(); } catch (Exception e) { e.printStackTrace(); } return new DataLoader(); } public void returnObject(DataLoader loader) { loader.reset(); factory.returnObject(loader); } @Override public DataLoader create() throws Exception { return new DataLoader(); } @Override public PooledObject<DataLoader> wrap(DataLoader obj) { return new DefaultPooledObject<DataLoader>(obj); } }
if (null == instance) { synchronized (DataLoaderFactory.class) { if (null == instance) { instance = new DataLoaderFactory(); } } } return instance;
119
398
56
454
21
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/DeleteCacheMagicHandler.java
DeleteCacheMagicHandler
isMagic
class DeleteCacheMagicHandler { private final CacheHandler cacheHandler; private final DeleteCacheAopProxyChain jp; private final CacheDeleteMagicKey[] cacheDeleteKeys; private final Object[] arguments; private final Method method; private final Object retVal; private final Object target; private final String methodName; private final Class<?>[] parameterTypes; public DeleteCacheMagicHandler(CacheHandler cacheHandler, DeleteCacheAopProxyChain jp, CacheDeleteMagicKey[] cacheDeleteKeys, Object retVal) { this.cacheHandler = cacheHandler; this.jp = jp; this.cacheDeleteKeys = cacheDeleteKeys; this.arguments = jp.getArgs(); this.method = jp.getMethod(); this.retVal = retVal; this.target = jp.getTarget(); this.methodName = jp.getMethod().getName(); this.parameterTypes = method.getParameterTypes(); } /** * @param cacheDeleteKey * @return * @throws Exception */ private void isMagic(CacheDeleteMagicKey cacheDeleteKey) throws Exception {<FILL_FUNCTION_BODY>} public List<List<CacheKeyTO>> getCacheKeyForMagic() throws Exception { List<List<CacheKeyTO>> lists = new ArrayList<>(cacheDeleteKeys.length); for (CacheDeleteMagicKey cacheDeleteKey : cacheDeleteKeys) { isMagic(cacheDeleteKey); String keyExpression = cacheDeleteKey.value(); String hfieldExpression = cacheDeleteKey.hfield(); // 只对返回值进行分割处理 if (parameterTypes.length == 0 || cacheDeleteKey.iterableArgIndex() < 0) { if (cacheDeleteKey.iterableReturnValue()) { lists.add(splitReturnValueOnly(cacheDeleteKey, retVal, keyExpression, hfieldExpression)); } continue; } int iterableArgIndex = cacheDeleteKey.iterableArgIndex(); // 只对参数进行分割处理 if (iterableArgIndex >= 0 && !cacheDeleteKey.iterableReturnValue()) { lists.add(splitArgOnly(cacheDeleteKey, retVal, keyExpression, hfieldExpression)); continue; } if (iterableArgIndex >= 0 && cacheDeleteKey.iterableReturnValue()) { } } return lists; } private List<CacheKeyTO> splitReturnValueOnly(CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception { if (null == retVal) { return Collections.emptyList(); } List<CacheKeyTO> list; if (retVal.getClass().isArray()) { Object[] newValues = (Object[]) retVal; list = new ArrayList<>(newValues.length); for (Object value : newValues) { if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, arguments, value)) { continue; } list.add(this.cacheHandler.getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, value, true)); } } else if (retVal instanceof Collection) { Collection<Object> newValues = (Collection<Object>) retVal; list = new ArrayList<>(newValues.size()); for (Object value : newValues) { if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, arguments, value)) { continue; } list.add(this.cacheHandler.getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, value, true)); } } else { return Collections.emptyList(); } return list; } private List<CacheKeyTO> splitArgOnly(CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception { int iterableArgIndex = cacheDeleteKey.iterableArgIndex(); Object tmpArg = arguments[iterableArgIndex]; List<CacheKeyTO> list = null; if (tmpArg instanceof Collection) { Collection<Object> iterableCollectionArg = (Collection<Object>) tmpArg; list = new ArrayList<>(iterableCollectionArg.size()); for (Object arg : iterableCollectionArg) { Optional<CacheKeyTO> tmp = getKey(arg, cacheDeleteKey, retVal, keyExpression, hfieldExpression); if (tmp.isPresent()) { list.add(tmp.get()); } } } else if (tmpArg.getClass().isArray()) { Object[] iterableArrayArg = (Object[]) tmpArg; list = new ArrayList<>(iterableArrayArg.length); for (Object arg : iterableArrayArg) { Optional<CacheKeyTO> tmp = getKey(arg, cacheDeleteKey, retVal, keyExpression, hfieldExpression); if (tmp.isPresent()) { list.add(tmp.get()); } } } else { return Collections.emptyList(); } return list; } private Optional<CacheKeyTO> getKey(Object arg, CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception { Object[] tmpArgs = new Object[arguments.length]; for (int i = 0; i < arguments.length; i++) { if (i == cacheDeleteKey.iterableArgIndex()) { tmpArgs[i] = arg; } else { tmpArgs[i] = arguments[i]; } } if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, tmpArgs, retVal)) { return Optional.empty(); } return Optional.of(this.cacheHandler.getCacheKey(target, methodName, tmpArgs, keyExpression, hfieldExpression, retVal, true)); } }
String key = cacheDeleteKey.value(); if (null == key || key.length() == 0) { throw new Exception("value不允许为空"); } int iterableArgIndex = cacheDeleteKey.iterableArgIndex(); if (parameterTypes.length > 0 && iterableArgIndex >= 0) { if (iterableArgIndex >= parameterTypes.length) { throw new Exception("iterableArgIndex必须小于参数长度:" + parameterTypes.length); } if (iterableArgIndex >= 0 && cacheDeleteKey.iterableReturnValue()) { throw new Exception("不支持iterableArgIndex大于0且iterableReturnValue=true的情况"); } Class<?> tmp = parameterTypes[iterableArgIndex]; if (tmp.isArray() || Collection.class.isAssignableFrom(tmp)) { //rv = true; } else { throw new Exception("magic模式下,参数" + iterableArgIndex + "必须是数组或Collection的类型"); } } if (cacheDeleteKey.iterableReturnValue()) { Class<?> returnType = method.getReturnType(); if (returnType.isArray() || Collection.class.isAssignableFrom(returnType)) { // rv = true; } else { throw new Exception("当iterableReturnValue=true时,返回值必须是数组或Collection的类型"); } }
394
1,481
358
1,839
23
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/RefreshHandler.java
RefreshTask
run
class RefreshTask implements Runnable { private final CacheAopProxyChain pjp; private final Cache cache; private final CacheKeyTO cacheKey; private final CacheWrapper<Object> cacheWrapper; private final Object[] arguments; public RefreshTask(CacheAopProxyChain pjp, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) throws Exception { this.pjp = pjp; this.cache = cache; this.cacheKey = cacheKey; this.cacheWrapper = cacheWrapper; if (cache.argumentsDeepCloneEnable()) { // 进行深度复制(因为是异步执行,防止外部修改参数值) this.arguments = (Object[]) cacheHandler.getCloner().deepCloneMethodArgs(pjp.getMethod(), pjp.getArgs()); } else { this.arguments = pjp.getArgs(); } } @Override public void run() {<FILL_FUNCTION_BODY>} public CacheKeyTO getCacheKey() { return cacheKey; } }
DataLoader dataLoader; if(cacheHandler.getAutoLoadConfig().isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); dataLoader = factory.getDataLoader(); } else { dataLoader = new DataLoader(); } CacheWrapper<Object> newCacheWrapper = null; boolean isFirst = false; try { newCacheWrapper = dataLoader.init(pjp, cacheKey, cache, cacheHandler, arguments).loadData() .getCacheWrapper(); } catch (Throwable ex) { log.error(ex.getMessage(), ex); } finally { // dataLoader 的数据必须在放回对象池之前获取 isFirst = dataLoader.isFirst(); if(cacheHandler.getAutoLoadConfig().isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); factory.returnObject(dataLoader); } } if (isFirst) { // 如果数据加载失败,则把旧数据进行续租 if (null == newCacheWrapper && null != cacheWrapper) { int newExpire = cacheWrapper.getExpire() / 2; if (newExpire < 120) { newExpire = 120; } newCacheWrapper = new CacheWrapper<Object>(cacheWrapper.getCacheObject(), newExpire); } try { if (null != newCacheWrapper) { cacheHandler.writeCache(pjp, arguments, cache, cacheKey, newCacheWrapper); } } catch (Throwable e) { log.error(e.getMessage(), e); } } refreshing.remove(cacheKey);
737
293
424
717
24
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-lock/autoload-cache-lock-jedis/src/main/java/com/jarvis/cache/lock/ShardedJedisLock.java
ShardedJedisLock
setnx
class ShardedJedisLock extends AbstractRedisLock { private ShardedJedisPool shardedJedisPool; public ShardedJedisLock(ShardedJedisPool shardedJedisPool) { this.shardedJedisPool = shardedJedisPool; } private void returnResource(ShardedJedis shardedJedis) { shardedJedis.close(); } @Override protected boolean setnx(String key, String val, int expire) {<FILL_FUNCTION_BODY>} @Override protected void del(String key) { ShardedJedis shardedJedis = null; try { shardedJedis = shardedJedisPool.getResource(); Jedis jedis = shardedJedis.getShard(key); jedis.del(key); } finally { returnResource(shardedJedis); } } }
ShardedJedis shardedJedis = null; try { shardedJedis = shardedJedisPool.getResource(); Jedis jedis = shardedJedis.getShard(key); return OK.equalsIgnoreCase(jedis.set(key, val, SetParams.setParams().nx().ex(expire))); } finally { returnResource(shardedJedis); }
99
254
113
367
25
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-lock/autoload-cache-lock-redis/src/main/java/com/jarvis/cache/lock/AbstractRedisLock.java
AbstractRedisLock
unlock
class AbstractRedisLock implements ILock { private static final Logger logger = LoggerFactory.getLogger(AbstractRedisLock.class); private static final ThreadLocal<Map<String, RedisLockInfo>> LOCK_START_TIME = new ThreadLocal<Map<String, RedisLockInfo>>() { @Override protected Map<String, RedisLockInfo> initialValue() { return new HashMap<>(4); } }; protected static final String OK = "OK"; protected static final String NX = "NX"; protected static final String EX = "EX"; /** * SETNX * * @param key key * @param val vale * @param expire 过期时间 * @return 是否设置成功 */ protected abstract boolean setnx(String key, String val, int expire); /** * DEL * * @param key key */ protected abstract void del(String key); @Override public boolean tryLock(String key, int lockExpire) { boolean locked = setnx(key, OK, lockExpire); if (locked) { Map<String, RedisLockInfo> startTimeMap = LOCK_START_TIME.get(); RedisLockInfo info = new RedisLockInfo(); info.setLeaseTime(lockExpire * 1000); info.setStartTime(System.currentTimeMillis()); startTimeMap.put(key, info); } return locked; } @Override public void unlock(String key) {<FILL_FUNCTION_BODY>} }
Map<String, RedisLockInfo> startTimeMap = LOCK_START_TIME.get(); RedisLockInfo info = null; if (null != startTimeMap) { info = startTimeMap.remove(key); } // 如果实际执行时长超过租约时间则不需要主到释放锁 long useTime = System.currentTimeMillis() - info.getStartTime(); if (null != info && useTime >= info.getLeaseTime()) { logger.warn("lock(" + key + ") run timeout, use time:" + useTime); return; } try { del(key); } catch (Throwable e) { }
183
423
175
598
26
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisClusterCacheManager.java
JedisClusterClient
hset
class JedisClusterClient implements IRedis { private final JedisCluster jedisCluster; private final AbstractRedisCacheManager cacheManager; public JedisClusterClient(JedisCluster jedisCluster, AbstractRedisCacheManager cacheManager) { this.jedisCluster = jedisCluster; this.cacheManager = cacheManager; } @Override public void close() throws IOException { } @Override public void set(byte[] key, byte[] value) { jedisCluster.set(key, value); } @Override public void setex(byte[] key, int seconds, byte[] value) { jedisCluster.setex(key, seconds, value); } @Override public void hset(byte[] key, byte[] field, byte[] value) { jedisCluster.hset(key, field, value); } @Override public void hset(byte[] key, byte[] field, byte[] value, int seconds) {<FILL_FUNCTION_BODY>} @Override public void mset(Collection<MSetParam> params) { RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) { @Override public void execute(JedisClusterPipeline pipeline) throws Exception { JedisUtil.executeMSet(pipeline, cacheManager, params); } }; try { retryableJedisClusterPipeline.sync(); } catch (Exception e) { log.error(e.getMessage(), e); } } @Override public byte[] get(byte[] key) { return jedisCluster.get(key); } @Override public byte[] hget(byte[] key, byte[] field) { return jedisCluster.hget(key, field); } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) throws Exception { RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) { @Override public void execute(JedisClusterPipeline pipeline) { JedisUtil.executeMGet(pipeline, keys); } }; return cacheManager.deserialize(keys, retryableJedisClusterPipeline.syncAndReturnAll(), returnType); } @Override public void delete(Set<CacheKeyTO> keys) { RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) { @Override public void execute(JedisClusterPipeline pipeline) { JedisUtil.executeDelete(pipeline, keys); } }; try { retryableJedisClusterPipeline.sync(); } catch (Exception e) { log.error(e.getMessage(), e); } } }
RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) { @Override public void execute(JedisClusterPipeline pipeline) { pipeline.hset(key, field, value); pipeline.expire(key, seconds); } }; try { retryableJedisClusterPipeline.sync(); } catch (Exception e) { log.error(e.getMessage(), e); }
207
793
132
925
27
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisClusterPipeline.java
JedisClusterPipeline
innerSync
class JedisClusterPipeline extends PipelineBase implements Closeable { private final JedisClusterInfoCache clusterInfoCache; /** * 根据顺序存储每个命令对应的Client */ private final Queue<Client> clients; /** * 用于缓存连接 */ private final Map<JedisPool, Jedis> jedisMap; public JedisClusterPipeline(JedisClusterInfoCache clusterInfoCache) { this.clusterInfoCache = clusterInfoCache; this.clients = new LinkedList<>(); this.jedisMap = new HashMap<>(3); } /** * 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化 */ protected void sync() { innerSync(null); } /** * 同步读取所有数据 并按命令顺序返回一个列表 * * @return 按照命令的顺序返回所有的数据 */ protected List<Object> syncAndReturnAll() { List<Object> responseList = new ArrayList<>(clients.size()); innerSync(responseList); return responseList; } private void innerSync(List<Object> formatted) {<FILL_FUNCTION_BODY>} @Override public void close() { clean(); clients.clear(); for (Jedis jedis : jedisMap.values()) { flushCachedData(jedis); jedis.close(); } jedisMap.clear(); } private void flushCachedData(Jedis jedis) { try { //FIXME 这个count怎么取值? 执行命令的个数?? jedis.getClient().getMany(jedisMap.size()); //jedis.getClient().getAll(); } catch (RuntimeException ex) { // 其中一个client出问题,后面出问题的几率较大 } } @Override protected Client getClient(String key) { byte[] bKey = SafeEncoder.encode(key); return getClient(bKey); } @Override protected Client getClient(byte[] key) { Client client = getClient(JedisClusterCRC16.getSlot(key)); clients.add(client); return client; } private Client getClient(int slot) { JedisPool pool = clusterInfoCache.getSlotPool(slot); // 根据pool从缓存中获取Jedis Jedis jedis = jedisMap.get(pool); if (null == jedis) { jedis = pool.getResource(); jedisMap.put(pool, jedis); } return jedis.getClient(); } public JedisClusterInfoCache getClusterInfoCache() { return clusterInfoCache; } public Queue<Client> getClients() { return clients; } public Map<JedisPool, Jedis> getJedisMap() { return jedisMap; } }
try { Response<?> response; Object data; for (Client client : clients) { response = generateResponse(client.getOne()); if (null != formatted) { data = response.get(); formatted.add(data); } } } catch (JedisRedirectionException jre) { throw jre; } finally { close(); }
220
824
107
931
28
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisUtil.java
JedisUtil
executeMSet
class JedisUtil { private static final Logger log = LoggerFactory.getLogger(JedisUtil.class); public static void executeMSet(PipelineBase pipeline, AbstractRedisCacheManager manager, Collection<MSetParam> params) throws Exception {<FILL_FUNCTION_BODY>} public static void executeMGet(PipelineBase pipeline, Set<CacheKeyTO> keys) { String hfield; String cacheKey; byte[] key; for (CacheKeyTO cacheKeyTO : keys) { cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { continue; } hfield = cacheKeyTO.getHfield(); key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey); if (null == hfield || hfield.isEmpty()) { pipeline.get(key); } else { pipeline.hget(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield)); } } } public static void executeDelete(PipelineBase pipeline, Set<CacheKeyTO> keys) { String hfield; String cacheKey; byte[] key; for (CacheKeyTO cacheKeyTO : keys) { cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { continue; } if (log.isDebugEnabled()) { log.debug("delete cache {}", cacheKey); } hfield = cacheKeyTO.getHfield(); key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey); if (null == hfield || hfield.isEmpty()) { pipeline.del(key); } else { pipeline.hdel(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield)); } } } }
CacheKeyTO cacheKeyTO; String cacheKey; String hfield; CacheWrapper<Object> result; byte[] key; byte[] val; for (MSetParam param : params) { if(null == param){ continue; } cacheKeyTO = param.getCacheKey(); cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { continue; } result = param.getResult(); hfield = cacheKeyTO.getHfield(); key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey); val = manager.getSerializer().serialize(result); if (null == hfield || hfield.isEmpty()) { int expire = result.getExpire(); if (expire == AbstractRedisCacheManager.NEVER_EXPIRE) { pipeline.set(key, val); } else if (expire > 0) { pipeline.setex(key, expire, val); } } else { int hExpire = manager.getHashExpire() < 0 ? result.getExpire() : manager.getHashExpire(); pipeline.hset(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield), val); if (hExpire > 0) { pipeline.expire(key, hExpire); } } }
516
490
364
854
29
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/RetryableJedisClusterPipeline.java
RetryableJedisClusterPipeline
syncAndReturnAll
class RetryableJedisClusterPipeline { /** * 部分字段没有对应的获取方法,只能采用反射来做 * 也可以去继承JedisCluster和JedisSlotBasedConnectionHandler来提供访问接口 **/ private static final Field FIELD_CONNECTION_HANDLER; private static final Field FIELD_CACHE; private static final Logger log = LoggerFactory.getLogger(JedisUtil.class); static { FIELD_CONNECTION_HANDLER = getField(BinaryJedisCluster.class, "connectionHandler"); FIELD_CACHE = getField(JedisClusterConnectionHandler.class, "cache"); } private final JedisSlotBasedConnectionHandler connectionHandler; private final JedisClusterInfoCache clusterInfoCache; private int maxAttempts = 1; public RetryableJedisClusterPipeline(JedisCluster jedisCluster) { connectionHandler = getValue(jedisCluster, FIELD_CONNECTION_HANDLER); clusterInfoCache = getValue(connectionHandler, FIELD_CACHE); } public abstract void execute(JedisClusterPipeline pipeline) throws Exception; /** * 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化 * @throws Exception redis 异常 */ public void sync() throws Exception { try { JedisClusterPipeline pipeline = new JedisClusterPipeline(clusterInfoCache); execute(pipeline); pipeline.sync(); } catch (JedisMovedDataException jre) { // if MOVED redirection occurred, rebuilds cluster's slot cache, // recommended by Redis cluster specification connectionHandler.renewSlotCache(); if (maxAttempts > 0) { maxAttempts--; sync(); return; } throw jre; } catch (Exception e) { throw e; } } /** * 同步读取所有数据 并按命令顺序返回一个列表 * * @return 按照命令的顺序返回所有的数据 * @throws Exception redis 异常 */ public List<Object> syncAndReturnAll() throws Exception {<FILL_FUNCTION_BODY>} private static Field getField(Class<?> cls, String fieldName) { try { Field field = cls.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (NoSuchFieldException | SecurityException e) { throw new RuntimeException("cannot find or access field '" + fieldName + "' from " + cls.getName(), e); } } @SuppressWarnings({"unchecked"}) private static <T> T getValue(Object obj, Field field) { try { return (T) field.get(obj); } catch (IllegalArgumentException | IllegalAccessException e) { log.error("get value fail", e); throw new RuntimeException(e); } } }
try { JedisClusterPipeline pipeline = new JedisClusterPipeline(clusterInfoCache); execute(pipeline); return pipeline.syncAndReturnAll(); } catch (JedisMovedDataException jre) { // if MOVED redirection occurred, rebuilds cluster's slot cache, // recommended by Redis cluster specification connectionHandler.renewSlotCache(); if (maxAttempts > 0) { maxAttempts--; return syncAndReturnAll(); } throw jre; } catch (Exception ex) { throw ex; }
223
806
155
961
30
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/ShardedJedisCacheManager.java
ShardedJedisClient
mset
class ShardedJedisClient implements IRedis { private static final Logger LOGGER = LoggerFactory.getLogger(ShardedJedisClient.class); private final ShardedJedis shardedJedis; private final AbstractRedisCacheManager cacheManager; public ShardedJedisClient(ShardedJedis shardedJedis, AbstractRedisCacheManager cacheManager) { this.shardedJedis = shardedJedis; this.cacheManager = cacheManager; } @Override public void close() throws IOException { if (null != shardedJedis) { shardedJedis.close(); } } @Override public void set(byte[] key, byte[] value) { Jedis jedis = shardedJedis.getShard(key); jedis.set(key, value); } @Override public void setex(byte[] key, int seconds, byte[] value) { Jedis jedis = shardedJedis.getShard(key); jedis.setex(key, seconds, value); } @Override public void hset(byte[] key, byte[] field, byte[] value) { Jedis jedis = shardedJedis.getShard(key); jedis.hset(key, field, value); } @Override public void hset(byte[] key, byte[] field, byte[] value, int seconds) { Jedis jedis = shardedJedis.getShard(key); Pipeline pipeline = jedis.pipelined(); pipeline.hset(key, field, value); pipeline.expire(key, seconds); pipeline.sync(); } @Override public void mset(Collection<MSetParam> params) {<FILL_FUNCTION_BODY>} @Override public byte[] get(byte[] key) { Jedis jedis = shardedJedis.getShard(key); return jedis.get(key); } @Override public byte[] hget(byte[] key, byte[] field) { Jedis jedis = shardedJedis.getShard(key); return jedis.hget(key, field); } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) throws Exception { ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); pipeline.setShardedJedis(shardedJedis); JedisUtil.executeMGet(pipeline, keys); Collection<Object> values = pipeline.syncAndReturnAll(); return cacheManager.deserialize(keys, values, returnType); } @Override public void delete(Set<CacheKeyTO> keys) { ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); pipeline.setShardedJedis(shardedJedis); JedisUtil.executeDelete(pipeline, keys); pipeline.sync(); } }
ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); pipeline.setShardedJedis(shardedJedis); try { JedisUtil.executeMSet(pipeline, this.cacheManager, params); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } pipeline.sync();
125
807
96
903
31
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisCacheManager.java
LettuceRedisClient
delete
class LettuceRedisClient implements IRedis { private final StatefulRedisConnection<byte[], byte[]> connection; private final AbstractRedisCacheManager cacheManager; public LettuceRedisClient(StatefulRedisConnection<byte[], byte[]> connection, AbstractRedisCacheManager cacheManager) { this.connection = connection; this.cacheManager = cacheManager; } @Override public void close() throws IOException { this.connection.close(); } @Override public void set(byte[] key, byte[] value) { connection.async().set(key, value); } @Override public void setex(byte[] key, int seconds, byte[] value) { connection.async().setex(key, seconds, value); } @Override public void hset(byte[] key, byte[] field, byte[] value) { connection.async().hset(key, field, value); } @Override public void hset(byte[] key, byte[] field, byte[] value, int seconds) { // 为了提升性能,开启pipeline this.connection.setAutoFlushCommands(false); RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); asyncCommands.hset(key, field, value); asyncCommands.expire(key, seconds); this.connection.flushCommands(); } @Override public void mset(Collection<MSetParam> params) { // 为了提升性能,开启pipeline this.connection.setAutoFlushCommands(false); RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); try { LettuceRedisUtil.executeMSet((AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, params); } catch (Exception e) { log.error(e.getMessage(), e); } finally { this.connection.flushCommands(); } } @Override public byte[] get(byte[] key) { try { return connection.async().get(key).get(); } catch (Exception e) { log.error(e.getMessage(), e); } return null; } @Override public byte[] hget(byte[] key, byte[] field) { try { return connection.async().hget(key, field).get(); } catch (Exception e) { log.error(e.getMessage(), e); } return null; } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) { RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); return LettuceRedisUtil.executeMGet(connection, (AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, returnType, keys); } @Override public void delete(Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>} }
// 为了提升性能,开启pipeline this.connection.setAutoFlushCommands(false); RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); try { for (CacheKeyTO cacheKeyTO : keys) { String cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { continue; } if (log.isDebugEnabled()) { log.debug("delete cache {}", cacheKey); } String hfield = cacheKeyTO.getHfield(); if (null == hfield || hfield.isEmpty()) { asyncCommands.del(KEY_SERIALIZER.serialize(cacheKey)); } else { asyncCommands.hdel(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield)); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { this.connection.flushCommands(); }
478
791
264
1,055
32
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisClusterCacheManager.java
LettuceRedisClusterClient
delete
class LettuceRedisClusterClient implements IRedis { private final StatefulRedisClusterConnection<byte[], byte[]> connection; private final AbstractRedisCacheManager cacheManager; public LettuceRedisClusterClient(StatefulRedisClusterConnection<byte[], byte[]> connection, AbstractRedisCacheManager cacheManager) { this.connection = connection; this.cacheManager = cacheManager; } @Override public void close() throws IOException { this.connection.close(); } @Override public void set(byte[] key, byte[] value) { connection.async().set(key, value); } @Override public void setex(byte[] key, int seconds, byte[] value) { connection.async().setex(key, seconds, value); } @Override public void hset(byte[] key, byte[] field, byte[] value) { connection.async().hset(key, field, value); } @Override public void hset(byte[] key, byte[] field, byte[] value, int seconds) { // 为了提升性能,开启pipeline this.connection.setAutoFlushCommands(false); RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); asyncCommands.hset(key, field, value); asyncCommands.expire(key, seconds); this.connection.flushCommands(); } @Override public void mset(Collection<MSetParam> params) { // 为了提升性能,开启pipeline this.connection.setAutoFlushCommands(false); RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); try { LettuceRedisUtil.executeMSet((AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, params); } catch (Exception e) { log.error(e.getMessage(), e); } finally { this.connection.flushCommands(); } } @Override public byte[] get(byte[] key) { try { return connection.async().get(key).get(); } catch (Exception e) { log.error(e.getMessage(), e); } return null; } @Override public byte[] hget(byte[] key, byte[] field) { try { return connection.async().hget(key, field).get(); } catch (Exception e) { log.error(e.getMessage(), e); } return null; } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) { RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); return LettuceRedisUtil.executeMGet(connection, (AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, returnType, keys); } @Override public void delete(Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>} }
// 为了提升性能,开启pipeline this.connection.setAutoFlushCommands(false); RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async(); try { for (CacheKeyTO cacheKeyTO : keys) { String cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.length() == 0) { continue; } if (log.isDebugEnabled()) { log.debug("delete cache {}", cacheKey); } String hfield = cacheKeyTO.getHfield(); if (null == hfield || hfield.length() == 0) { asyncCommands.del(KEY_SERIALIZER.serialize(cacheKey)); } else { asyncCommands.hdel(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield)); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { this.connection.flushCommands(); }
482
805
273
1,078
33
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisUtil.java
LettuceRedisUtil
executeMGet
class LettuceRedisUtil { public static void executeMSet(AbstractRedisAsyncCommands<byte[], byte[]> pipeline, AbstractRedisCacheManager manager, Collection<MSetParam> params) throws Exception { CacheKeyTO cacheKeyTO; String cacheKey; String hfield; CacheWrapper<Object> result; byte[] key; byte[] val; for (MSetParam param : params) { if (null == param) { continue; } cacheKeyTO = param.getCacheKey(); cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { continue; } result = param.getResult(); hfield = cacheKeyTO.getHfield(); key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey); val = manager.getSerializer().serialize(result); if (null == hfield || hfield.isEmpty()) { int expire = result.getExpire(); if (expire == AbstractRedisCacheManager.NEVER_EXPIRE) { pipeline.set(key, val); } else if (expire > 0) { pipeline.setex(key, expire, val); } } else { int hExpire = manager.getHashExpire() < 0 ? result.getExpire() : manager.getHashExpire(); pipeline.hset(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield), val); if (hExpire > 0) { pipeline.expire(key, hExpire); } } } } public static Map<CacheKeyTO, CacheWrapper<Object>> executeMGet(StatefulConnection<byte[], byte[]> connection, AbstractRedisAsyncCommands<byte[], byte[]> asyncCommands, AbstractRedisCacheManager cacheManager, Type returnType, Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>} }
String hfield; String cacheKey; byte[] key; RedisFuture<byte[]>[] futures = new RedisFuture[keys.size()]; try { // 为了提升性能,开启pipeline connection.setAutoFlushCommands(false); int i = 0; for (CacheKeyTO cacheKeyTO : keys) { cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { continue; } hfield = cacheKeyTO.getHfield(); key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey); if (null == hfield || hfield.isEmpty()) { futures[i] = asyncCommands.get(key); } else { futures[i] = asyncCommands.hget(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield)); } i++; } } finally { connection.flushCommands(); } Map<CacheKeyTO, CacheWrapper<Object>> res = new HashMap<>(keys.size()); int i = 0; for (CacheKeyTO cacheKeyTO : keys) { RedisFuture<byte[]> future = futures[i]; try { byte[] data = future.get(); if (null == data || data.length == 0) { continue; } CacheWrapper<Object> value = (CacheWrapper<Object>)cacheManager.getSerializer().deserialize(data, returnType); if (null != value) { res.put(cacheKeyTO, value); } } catch (Exception e) { e.printStackTrace(); } i++; } return res;
675
501
449
950
36
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-memcache/src/main/java/com/jarvis/cache/memcache/MemcachedCacheManager.java
MemcachedCacheManager
delete
class MemcachedCacheManager implements ICacheManager { private MemcachedClient memcachedClient; public MemcachedCacheManager() { } @Override public void setCache(final CacheKeyTO cacheKeyTO, final CacheWrapper<Object> result, final Method method) throws CacheCenterConnectionException { if (null == cacheKeyTO) { return; } String cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { return; } String hfield = cacheKeyTO.getHfield(); if (null != hfield && hfield.length() > 0) { throw new RuntimeException("memcached does not support hash cache."); } if (result.getExpire() >= 0) { memcachedClient.set(cacheKey, result.getExpire(), result); } } @Override public void mset(final Method method, final Collection<MSetParam> params) throws CacheCenterConnectionException { if (null == params || params.isEmpty()) { return; } for (MSetParam param : params) { if (null == param) { continue; } this.setCache(param.getCacheKey(), param.getResult(), method); } } @SuppressWarnings("unchecked") @Override public CacheWrapper<Object> get(final CacheKeyTO cacheKeyTO, Method method) throws CacheCenterConnectionException { if (null == cacheKeyTO) { return null; } String cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { return null; } String hfield = cacheKeyTO.getHfield(); if (null != hfield && hfield.length() > 0) { throw new RuntimeException("memcached does not support hash cache."); } return (CacheWrapper<Object>) memcachedClient.get(cacheKey); } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(final Method method, final Type returnType, final Set<CacheKeyTO> keys) throws CacheCenterConnectionException { if (null == keys || keys.isEmpty()) { return Collections.emptyMap(); } Map<String, CacheKeyTO> keyMap = new HashMap<>(keys.size()); for (CacheKeyTO key : keys) { keyMap.put(key.getCacheKey(), key); } Map<String, Object> values = memcachedClient.getBulk(keyMap.keySet()); if (null == values || values.isEmpty()) { return null; } Map<CacheKeyTO, CacheWrapper<Object>> res = new HashMap<>(values.size()); Iterator<Map.Entry<String, CacheKeyTO>> keyMapIt = keyMap.entrySet().iterator(); while (keyMapIt.hasNext()) { Map.Entry<String, CacheKeyTO> item = keyMapIt.next(); CacheWrapper<Object> value = (CacheWrapper<Object>) values.get(item.getKey()); if (null != value) { res.put(item.getValue(), value); } } return res; } @Override public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException {<FILL_FUNCTION_BODY>} public MemcachedClient getMemcachedClient() { return memcachedClient; } public void setMemcachedClient(MemcachedClient memcachedClient) { this.memcachedClient = memcachedClient; } }
if (null == memcachedClient || null == keys || keys.isEmpty()) { return; } String hfield; for (CacheKeyTO cacheKeyTO : keys) { if (null == cacheKeyTO) { continue; } String cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { continue; } hfield = cacheKeyTO.getHfield(); if (null != hfield && hfield.length() > 0) { throw new RuntimeException("memcached does not support hash cache."); } try { String allKeysPattern = "*"; if (allKeysPattern.equals(cacheKey)) { memcachedClient.flush(); } else { memcachedClient.delete(cacheKey); } } catch (Exception e) { e.printStackTrace(); } }
415
921
235
1,156
37
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-redis/src/main/java/com/jarvis/cache/redis/AbstractRedisCacheManager.java
AbstractRedisCacheManager
setCache
class AbstractRedisCacheManager implements ICacheManager { public static final StringSerializer KEY_SERIALIZER = new StringSerializer(); private static final Logger log = LoggerFactory.getLogger(AbstractRedisCacheManager.class); /** * Hash的缓存时长:等于0时永久缓存;大于0时,主要是为了防止一些已经不用的缓存占用内存;hashExpire小于0时,则使用@Cache中设置的expire值(默认值为-1)。 */ protected int hashExpire = -1; protected final ISerializer<Object> serializer; public AbstractRedisCacheManager(ISerializer<Object> serializer) { this.serializer = serializer; } protected abstract IRedis getRedis(); @Override public void setCache(final CacheKeyTO cacheKeyTO, final CacheWrapper<Object> result, final Method method) throws CacheCenterConnectionException {<FILL_FUNCTION_BODY>} @Override public void mset(final Method method, final Collection<MSetParam> params) { if (null == params || params.isEmpty()) { return; } try (IRedis redis = getRedis()) { redis.mset(params); } catch (Exception ex) { ex.printStackTrace(); } } @SuppressWarnings("unchecked") @Override public CacheWrapper<Object> get(final CacheKeyTO cacheKeyTO, final Method method) throws CacheCenterConnectionException { if (null == cacheKeyTO) { return null; } String cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { return null; } CacheWrapper<Object> res = null; String hfield; Type returnType = null; try (IRedis redis = getRedis()) { byte[] val; hfield = cacheKeyTO.getHfield(); if (null == hfield || hfield.isEmpty()) { val = redis.get(KEY_SERIALIZER.serialize(cacheKey)); } else { val = redis.hget(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield)); } if (null != method) { returnType = method.getGenericReturnType(); } res = (CacheWrapper<Object>) serializer.deserialize(val, returnType); } catch (Exception ex) { ex.printStackTrace(); } return res; } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(final Method method, final Type returnType, final Set<CacheKeyTO> keys) { if (null == keys || keys.isEmpty()) { return Collections.emptyMap(); } try (IRedis redis = getRedis()) { return redis.mget(returnType, keys); } catch (Exception ex) { ex.printStackTrace(); } return null; } public Map<CacheKeyTO, CacheWrapper<Object>> deserialize(Set<CacheKeyTO> keys, Collection<Object> values, Type returnType) throws Exception { if (null == values || values.isEmpty()) { return Collections.emptyMap(); } CacheWrapper<Object> tmp; Map<CacheKeyTO, CacheWrapper<Object>> res = new HashMap<>(keys.size()); Iterator<CacheKeyTO> keysIt = keys.iterator(); for (Object value : values) { CacheKeyTO cacheKeyTO = keysIt.next(); if (null == value) { continue; } if (!(value instanceof byte[])) { log.warn("the data from redis is not byte[] but " + value.getClass().getName()); continue; } tmp = (CacheWrapper<Object>) serializer.deserialize((byte[]) value, returnType); if (null != tmp) { res.put(cacheKeyTO, tmp); } } return res; } @Override public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException { if (null == keys || keys.isEmpty()) { return; } try (IRedis redis = getRedis()) { redis.delete(keys); } catch (Exception ex) { ex.printStackTrace(); } } public int getHashExpire() { return hashExpire; } public void setHashExpire(int hashExpire) { if (hashExpire < 0) { return; } this.hashExpire = hashExpire; } public ISerializer<Object> getSerializer() { return serializer; } }
if (null == cacheKeyTO) { return; } String cacheKey = cacheKeyTO.getCacheKey(); if (null == cacheKey || cacheKey.isEmpty()) { return; } try (IRedis redis = getRedis()) { String hfield = cacheKeyTO.getHfield(); byte[] key = KEY_SERIALIZER.serialize(cacheKey); byte[] val = serializer.serialize(result); if (null == hfield || hfield.isEmpty()) { int expire = result.getExpire(); if (expire == NEVER_EXPIRE) { redis.set(key, val); } else if (expire > 0) { redis.setex(key, expire, val); } } else { byte[] field = KEY_SERIALIZER.serialize(hfield); int hExpire = hashExpire < 0 ? result.getExpire() : hashExpire; if (hExpire == NEVER_EXPIRE) { redis.hset(key, field, val); } else if (hExpire > 0) { redis.hset(key, field, val, hExpire); } } } catch (Exception ex) { ex.printStackTrace(); }
483
1,232
337
1,569
39
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-script/autoload-cache-script-js/src/main/java/com/jarvis/cache/script/JavaScriptParser.java
JavaScriptParser
getElValue
class JavaScriptParser extends AbstractScriptParser { private final ScriptEngineManager manager = new ScriptEngineManager(); private final ConcurrentHashMap<String, CompiledScript> expCache = new ConcurrentHashMap<String, CompiledScript>(); private final StringBuffer funcs = new StringBuffer(); private static int versionCode; private final ScriptEngine engine; public JavaScriptParser() { engine = manager.getEngineByName("javascript"); try { addFunction(HASH, CacheUtil.class.getDeclaredMethod("getUniqueHashStr", new Class[]{Object.class})); addFunction(EMPTY, CacheUtil.class.getDeclaredMethod("isEmpty", new Class[]{Object.class})); } catch (Exception e) { e.printStackTrace(); } } @Override public void addFunction(String name, Method method) { try { String clsName = method.getDeclaringClass().getName(); String methodName = method.getName(); funcs.append("function " + name + "(obj){return " + clsName + "." + methodName + "(obj);}"); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") @Override public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal, Class<T> valueType) throws Exception {<FILL_FUNCTION_BODY>} }
Bindings bindings = new SimpleBindings(); bindings.put(TARGET, target); bindings.put(ARGS, arguments); if (hasRetVal) { bindings.put(RET_VAL, retVal); } CompiledScript script = expCache.get(exp); if (null != script) { return (T) script.eval(bindings); } if (engine instanceof Compilable) { Compilable compEngine = (Compilable) engine; script = compEngine.compile(funcs + exp); expCache.put(exp, script); return (T) script.eval(bindings); } else { return (T) engine.eval(funcs + exp, bindings); }
217
378
197
575
40
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-script/autoload-cache-script-ognl/src/main/java/com/jarvis/cache/script/OgnlParser.java
OgnlParser
getElValue
class OgnlParser extends AbstractScriptParser { private final ConcurrentHashMap<String, Object> EXPRESSION_CACHE = new ConcurrentHashMap<String, Object>(); private final ConcurrentHashMap<String, Class<?>> funcs = new ConcurrentHashMap<String, Class<?>>(8); public OgnlParser() { } @Override public void addFunction(String name, Method method) { funcs.put(name, method.getDeclaringClass()); } @SuppressWarnings("unchecked") @Override public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal, Class<T> valueType) throws Exception {<FILL_FUNCTION_BODY>} }
if (valueType.equals(String.class)) { if (exp.indexOf("#") == -1 && exp.indexOf("@") == -1 && exp.indexOf("'") == -1) {// 如果不是表达式,直接返回字符串 return (T) exp; } } Object object = EXPRESSION_CACHE.get(exp); if (null == object) { String className = CacheUtil.class.getName(); String exp2 = exp.replaceAll("@@" + HASH + "\\(", "@" + className + "@getUniqueHashStr("); exp2 = exp2.replaceAll("@@" + EMPTY + "\\(", "@" + className + "@isEmpty("); Iterator<Map.Entry<String, Class<?>>> it = funcs.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Class<?>> entry = it.next(); className = entry.getValue().getName(); exp2 = exp2.replaceAll("@@" + entry.getKey() + "\\(", "@" + className + "@" + entry.getKey() + "("); } object = Ognl.parseExpression(exp2); EXPRESSION_CACHE.put(exp, object); } Map<String, Object> values = new HashMap<String, Object>(2); values.put(TARGET, target); values.put(ARGS, arguments); if (hasRetVal) { values.put(RET_VAL, retVal); } OgnlContext context = new OgnlContext(values); context.setRoot(arguments); Object res = Ognl.getValue(object, context, context.getRoot(), valueType); return (T) res;
416
202
454
656
41
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-script/autoload-cache-script-springel/src/main/java/com/jarvis/cache/script/SpringELParser.java
SpringELParser
getElValue
class SpringELParser extends AbstractScriptParser { /** * # 号 */ private static final String POUND = "#"; /** * 撇号 */ private static final String apostrophe = "'"; private final ExpressionParser parser = new SpelExpressionParser(); private final ConcurrentHashMap<String, Expression> expCache = new ConcurrentHashMap<String, Expression>(); private static Method hash = null; private static Method empty = null; static { try { hash = CacheUtil.class.getDeclaredMethod("getUniqueHashStr", new Class[]{Object.class}); empty = CacheUtil.class.getDeclaredMethod("isEmpty", new Class[]{Object.class}); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } private final ConcurrentHashMap<String, Method> funcs = new ConcurrentHashMap<String, Method>(8); /** * @param name 方法名 * @param method 方法 */ @Override public void addFunction(String name, Method method) { funcs.put(name, method); } @SuppressWarnings("unchecked") @Override public <T> T getElValue(String keySpEL, Object target, Object[] arguments, Object retVal, boolean hasRetVal, Class<T> valueType) throws Exception {<FILL_FUNCTION_BODY>} }
if (valueType.equals(String.class)) { // 如果不是表达式,直接返回字符串 if (keySpEL.indexOf(POUND) == -1 && keySpEL.indexOf("'") == -1) { return (T) keySpEL; } } StandardEvaluationContext context = new StandardEvaluationContext(); context.registerFunction(HASH, hash); context.registerFunction(EMPTY, empty); Iterator<Map.Entry<String, Method>> it = funcs.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Method> entry = it.next(); context.registerFunction(entry.getKey(), entry.getValue()); } context.setVariable(TARGET, target); context.setVariable(ARGS, arguments); if (hasRetVal) { context.setVariable(RET_VAL, retVal); } Expression expression = expCache.get(keySpEL); if (null == expression) { expression = parser.parseExpression(keySpEL); expCache.put(keySpEL, expression); } return expression.getValue(context, valueType);
292
409
302
711
42
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/clone/Cloning.java
Cloning
deepClone
class Cloning implements ICloner { private final Cloner cloner = new Cloner(); @Override public Object deepClone(Object obj, final Type type) throws Exception {<FILL_FUNCTION_BODY>} @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception { if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Object[] res = new Object[args.length]; int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { res[i] = deepClone(args[i], null); } return res; } }
if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } if (clazz.isArray()) { Object[] arr = (Object[]) obj; Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length] : (Object[]) Array.newInstance(clazz.getComponentType(), arr.length); for (int i = 0; i < arr.length; i++) { res[i] = deepClone(arr[i], null); } return res; } return cloner.deepClone(obj);
349
254
301
555
43
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/compress/CommonsCompressor.java
CommonsCompressor
compress
class CommonsCompressor implements ICompressor { private static final int BUFFER = 1024; private static final CompressorStreamFactory FACTORY = new CompressorStreamFactory(); private String name; public CommonsCompressor(String name) { this.name = name; } @Override public byte[] compress(ByteArrayInputStream bais) throws Exception {<FILL_FUNCTION_BODY>} @Override public byte[] decompress(ByteArrayInputStream bais) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); CompressorInputStream cis = FACTORY.createCompressorInputStream(name, bais); int len; byte buf[] = new byte[BUFFER]; while ((len = cis.read(buf, 0, BUFFER)) != -1) { baos.write(buf, 0, len); } cis.close(); byte[] output = baos.toByteArray(); baos.flush(); baos.close(); bais.close(); return output; } }
ByteArrayOutputStream baos = new ByteArrayOutputStream(); CompressorOutputStream cos = FACTORY.createCompressorOutputStream(name, baos); int len; byte buf[] = new byte[BUFFER]; while ((len = bais.read(buf, 0, BUFFER)) != -1) { cos.write(buf, 0, len); } cos.flush(); cos.close(); byte[] output = baos.toByteArray(); baos.flush(); baos.close(); bais.close(); return output;
148
284
148
432
44
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/serializer/CompressorSerializer.java
CompressorSerializer
deserialize
class CompressorSerializer implements ISerializer<Object> { private static final int DEFAULT_COMPRESSION_THRESHOLD = 16384; private int compressionThreshold = DEFAULT_COMPRESSION_THRESHOLD; private final ISerializer<Object> serializer; private final ICompressor compressor; public CompressorSerializer(ISerializer<Object> serializer) { this.serializer = serializer; this.compressor = new CommonsCompressor(CompressorStreamFactory.GZIP); } public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold) { this.serializer = serializer; this.compressionThreshold = compressionThreshold; this.compressor = new CommonsCompressor(CompressorStreamFactory.GZIP); } public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold, String compressType) { this.serializer = serializer; this.compressionThreshold = compressionThreshold; this.compressor = new CommonsCompressor(compressType); } public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold, ICompressor compressor) { this.serializer = serializer; this.compressionThreshold = compressionThreshold; this.compressor = compressor; } @Override public byte[] serialize(final Object obj) throws Exception { if (null == obj) { return null; } byte[] data = serializer.serialize(obj); byte flag = 0; if (data.length > compressionThreshold) { data = compressor.compress(new ByteArrayInputStream(data)); flag = 1; } byte[] out = new byte[data.length + 1]; out[0] = flag; System.arraycopy(data, 0, out, 1, data.length); return out; } @Override public Object deserialize(final byte[] bytes, final Type returnType) throws Exception {<FILL_FUNCTION_BODY>} @Override public Object deepClone(Object obj, final Type type) throws Exception { return serializer.deepClone(obj, type); } @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception { return serializer.deepCloneMethodArgs(method, args); } }
if (null == bytes || bytes.length == 0) { return null; } byte flag = bytes[0]; byte[] data; if (flag == 0) { data = new byte[bytes.length - 1]; System.arraycopy(bytes, 1, data, 0, data.length); } else { data = compressor.decompress(new ByteArrayInputStream(bytes, 1, bytes.length - 1)); } return serializer.deserialize(data, returnType);
154
627
136
763
45
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/serializer/StringSerializer.java
StringSerializer
deepClone
class StringSerializer implements ISerializer<String> { private final Charset charset; public StringSerializer() { this(StandardCharsets.UTF_8); } public StringSerializer(Charset charset) { this.charset = charset; } @Override public String deserialize(byte[] bytes, Type returnType) { return (bytes == null ? null : new String(bytes, charset)); } @Override public byte[] serialize(String string) { return (string == null ? null : string.getBytes(charset)); } @Override public Object deepClone(Object obj, final Type type) {<FILL_FUNCTION_BODY>} @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) { return (Object[]) deepClone(args, null); } }
if (null == obj) { return obj; } String str = (String) obj; return String.copyValueOf(str.toCharArray());
59
224
45
269
46
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-fastjson/src/main/java/com/jarvis/cache/serializer/FastjsonSerializer.java
FastjsonSerializer
deepClone
class FastjsonSerializer implements ISerializer<Object> { private final Charset charset; private static final SerializerFeature[] FEATURES = {SerializerFeature.DisableCircularReferenceDetect}; private static final Map<Type, ParameterizedTypeImpl> TYPE_CACHE = new ConcurrentHashMap<>(1024); public FastjsonSerializer() { this(StandardCharsets.UTF_8); } public FastjsonSerializer(Charset charset) { this.charset = charset; } @Override public byte[] serialize(final Object obj) throws Exception { if (obj == null) { return null; } String json = JSON.toJSONString(obj, FEATURES); return json.getBytes(charset); } @Override public Object deserialize(final byte[] bytes, final Type returnType) throws Exception { if (null == bytes || bytes.length == 0) { return null; } ParameterizedTypeImpl type = TYPE_CACHE.get(returnType); if (null == type) { Type[] agsType = new Type[]{returnType}; type = ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null); TYPE_CACHE.put(returnType, type); } String json = new String(bytes, charset); return JSON.parseObject(json, type); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Object deepClone(Object obj, final Type type) throws Exception {<FILL_FUNCTION_BODY>} @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception { if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Class<?> clazz = args.getClass(); Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[args.length] : (Object[]) Array.newInstance(clazz.getComponentType(), args.length); int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { Type genericParameterType = genericParameterTypes[i]; Object obj = args[i]; if (genericParameterType instanceof ParameterizedType) { String json = JSON.toJSONString(obj, FEATURES); res[i] = JSON.parseObject(json, genericParameterType); } else { res[i] = deepClone(obj, null); } } return res; } }
if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } // List/Map在编译时类型会被擦除,导致List<Object>反序列化后变为List<JSONObject> if (null != type && !(obj instanceof Collection) && !(obj instanceof Map)) { String json = JSON.toJSONString(obj, FEATURES); return JSON.parseObject(json, type); } if (clazz.isArray()) { Object[] arr = (Object[]) obj; Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length] : (Object[]) Array.newInstance(clazz.getComponentType(), arr.length); for (int i = 0; i < arr.length; i++) { res[i] = deepClone(arr[i], null); } return res; } else if (obj instanceof Collection) { Collection<?> tempCol = (Collection<?>) obj; Collection res = tempCol.getClass().newInstance(); Iterator<?> it = tempCol.iterator(); while (it.hasNext()) { Object val = deepClone(it.next(), null); res.add(val); } return res; } else if (obj instanceof Map) { Map tempMap = (Map) obj; Map res = tempMap.getClass().newInstance(); Iterator it = tempMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Entry) it.next(); Object key = entry.getKey(); Object val = entry.getValue(); res.put(deepClone(key, null), deepClone(val, null)); } return res; } else if (obj instanceof CacheWrapper) { CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj; CacheWrapper<Object> res = new CacheWrapper<Object>(); res.setExpire(wrapper.getExpire()); res.setLastLoadTime(wrapper.getLastLoadTime()); res.setCacheObject(deepClone(wrapper.getCacheObject(), null)); return res; } else { String json = JSON.toJSONString(obj, FEATURES); return JSON.parseObject(json, clazz); }
854
739
735
1,474
47
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/HessianSerializer.java
HessianSerializer
deepCloneMethodArgs
class HessianSerializer implements ISerializer<Object> { private static final SerializerFactory SERIALIZER_FACTORY = new SerializerFactory(); static { SERIALIZER_FACTORY.addFactory(new HessionBigDecimalSerializerFactory()); SERIALIZER_FACTORY.addFactory(new HessionSoftReferenceSerializerFactory()); } /** * 添加自定义SerializerFactory * * @param factory AbstractSerializerFactory */ public void addSerializerFactory(AbstractSerializerFactory factory) { SERIALIZER_FACTORY.addFactory(factory); } @Override public byte[] serialize(final Object obj) throws Exception { if (obj == null) { return null; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); AbstractHessianOutput output = new Hessian2Output(outputStream); output.setSerializerFactory(SERIALIZER_FACTORY); // 将对象写到流里 output.writeObject(obj); output.flush(); byte[] val = outputStream.toByteArray(); output.close(); return val; } @Override public Object deserialize(final byte[] bytes, final Type returnType) throws Exception { if (null == bytes || bytes.length == 0) { return null; } ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); AbstractHessianInput input = new Hessian2Input(inputStream); input.setSerializerFactory(SERIALIZER_FACTORY); Object obj = input.readObject(); input.close(); return obj; } @Override public Object deepClone(Object obj, final Type type) throws Exception { if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } return deserialize(serialize(obj), null); } @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Object[] res = new Object[args.length]; int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { res[i] = deepClone(args[i], null); } return res;
193
655
167
822
48
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/SoftReferenceDeserializer.java
SoftReferenceDeserializer
readObject
class SoftReferenceDeserializer extends AbstractMapDeserializer { @Override public Object readObject(AbstractHessianInput in, Object[] fields) throws IOException {<FILL_FUNCTION_BODY>} protected SoftReference<Object> instantiate() throws Exception { Object obj = new Object(); return new SoftReference<Object>(obj); } }
try { SoftReference<Object> obj = instantiate(); in.addRef(obj); Object value = in.readObject(); obj = null; return new SoftReference<Object>(value); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(e); }
143
93
92
185
49
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/SoftReferenceSerializer.java
SoftReferenceSerializer
writeObject
class SoftReferenceSerializer extends AbstractSerializer implements ObjectSerializer { @Override public Serializer getObjectSerializer() { return this; } @Override public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {<FILL_FUNCTION_BODY>} }
if (out.addRef(obj)) { return; } @SuppressWarnings("unchecked") SoftReference<Object> data = (SoftReference<Object>) obj; int refV = out.writeObjectBegin(SoftReference.class.getName()); if (refV == -1) { out.writeInt(1); out.writeString("ref"); out.writeObjectBegin(SoftReference.class.getName()); } if (data != null) { Object ref = data.get(); if (null != ref) { out.writeObject(ref); } else { out.writeNull(); } } else { out.writeNull(); }
253
74
188
262
50
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceDeserializer.java
WeakReferenceDeserializer
readObject
class WeakReferenceDeserializer extends AbstractMapDeserializer { @Override public Object readObject(AbstractHessianInput in, Object[] fields) throws IOException {<FILL_FUNCTION_BODY>} protected WeakReference<Object> instantiate() throws Exception { Object obj = new Object(); return new WeakReference<Object>(obj); } }
try { WeakReference<Object> obj = instantiate(); in.addRef(obj); Object value = in.readObject(); obj = null; return new WeakReference<Object>(value); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(e); }
143
96
94
190
51
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceSerializer.java
WeakReferenceSerializer
writeObject
class WeakReferenceSerializer extends AbstractSerializer implements ObjectSerializer { @Override public Serializer getObjectSerializer() { return this; } @Override public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {<FILL_FUNCTION_BODY>} }
if (out.addRef(obj)) { return; } @SuppressWarnings("unchecked") WeakReference<Object> data = (WeakReference<Object>) obj; int refV = out.writeObjectBegin(WeakReference.class.getName()); if (refV == -1) { out.writeInt(1); out.writeString("ref"); out.writeObjectBegin(WeakReference.class.getName()); } if (data != null) { Object ref = data.get(); if (null != ref) { out.writeObject(ref); } else { out.writeNull(); } } else { out.writeNull(); }
253
75
192
267
52
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jackson-msgpack/src/main/java/com/jarvis/cache/serializer/JacksonMsgpackSerializer.java
JacksonMsgpackSerializer
deepClone
class JacksonMsgpackSerializer implements ISerializer<Object> { private static final ObjectMapper MAPPER = new ObjectMapper(new MessagePackFactory()); @Override public byte[] serialize(Object obj) throws Exception { if (obj == null) { return null; } return MAPPER.writeValueAsBytes(obj); } @Override public Object deserialize(byte[] bytes, Type returnType) throws Exception { if (null == bytes || bytes.length == 0) { return null; } Type[] agsType = new Type[]{returnType}; JavaType javaType = MAPPER.getTypeFactory() .constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null)); return MAPPER.readValue(bytes, javaType); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Object deepClone(Object obj, final Type type) throws Exception {<FILL_FUNCTION_BODY>} @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception { if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Class<?> clazz = args.getClass(); Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[args.length] : (Object[]) Array.newInstance(clazz.getComponentType(), args.length); int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { Type genericParameterType = genericParameterTypes[i]; Object obj = args[i]; if (genericParameterType instanceof ParameterizedType) { byte[] tmp = MAPPER.writeValueAsBytes(obj); JavaType javaType = MAPPER.getTypeFactory().constructType(genericParameterType); res[i] = MAPPER.readValue(tmp, javaType); } else { res[i] = deepClone(obj, null); } } return res; } }
if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } if (null != type) { byte[] tmp = MAPPER.writeValueAsBytes(obj); JavaType javaType = MAPPER.getTypeFactory().constructType(type); return MAPPER.readValue(tmp, javaType); } if (clazz.isArray()) { Object[] arr = (Object[]) obj; Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length] : (Object[]) Array.newInstance(clazz.getComponentType(), arr.length); for (int i = 0; i < arr.length; i++) { res[i] = deepClone(arr[i], null); } return res; } else if (obj instanceof Collection) { Collection<?> tempCol = (Collection<?>) obj; Collection res = tempCol.getClass().newInstance(); Iterator<?> it = tempCol.iterator(); while (it.hasNext()) { Object val = deepClone(it.next(), null); res.add(val); } return res; } else if (obj instanceof Map) { Map tempMap = (Map) obj; Map res = tempMap.getClass().newInstance(); Iterator it = tempMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Entry) it.next(); Object key = entry.getKey(); Object val = entry.getValue(); res.put(deepClone(key, null), deepClone(val, null)); } return res; } else if (obj instanceof CacheWrapper) { CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj; CacheWrapper<Object> res = new CacheWrapper<Object>(); res.setExpire(wrapper.getExpire()); res.setLastLoadTime(wrapper.getLastLoadTime()); res.setCacheObject(deepClone(wrapper.getCacheObject(), null)); return res; } else { byte[] tmp = MAPPER.writeValueAsBytes(obj); return MAPPER.readValue(tmp, clazz); }
850
610
714
1,324
53
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jackson/src/main/java/com/jarvis/cache/serializer/JacksonJsonSerializer.java
NullValueSerializer
deepClone
class NullValueSerializer extends StdSerializer<NullValue> { private static final long serialVersionUID = 1999052150548658808L; private final String classIdentifier; /** * @param classIdentifier can be {@literal null} and will be defaulted * to {@code @class}. */ NullValueSerializer(String classIdentifier) { super(NullValue.class); this.classIdentifier = StringUtil.hasText(classIdentifier) ? classIdentifier : "@class"; } /* * (non-Javadoc) * @see * com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java. * lang.Object, com.fasterxml.jackson.core.JsonGenerator, * com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeStringField(classIdentifier, NullValue.class.getName()); jgen.writeEndObject(); } } @Override public byte[] serialize(final Object obj) throws Exception { if (obj == null) { return null; } return MAPPER.writeValueAsBytes(obj); } @Override public Object deserialize(final byte[] bytes, final Type returnType) throws Exception { if (null == bytes || bytes.length == 0) { return null; } Type[] agsType = new Type[]{returnType}; JavaType javaType = MAPPER.getTypeFactory() .constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null)); return MAPPER.readValue(bytes, javaType); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Object deepClone(Object obj, final Type type) throws Exception {<FILL_FUNCTION_BODY>
if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } if (null != type) { String json = MAPPER.writeValueAsString(obj); JavaType javaType = MAPPER.getTypeFactory().constructType(type); return MAPPER.readValue(json, javaType); } if (clazz.isArray()) { Object[] arr = (Object[]) obj; Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length] : (Object[]) Array.newInstance(clazz.getComponentType(), arr.length); for (int i = 0; i < arr.length; i++) { res[i] = deepClone(arr[i], null); } return res; } else if (obj instanceof Collection) { Collection<?> tempCol = (Collection<?>) obj; Collection res = tempCol.getClass().newInstance(); Iterator<?> it = tempCol.iterator(); while (it.hasNext()) { Object val = deepClone(it.next(), null); res.add(val); } return res; } else if (obj instanceof Map) { Map tempMap = (Map) obj; Map res = tempMap.getClass().newInstance(); Iterator it = tempMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Entry) it.next(); Object key = entry.getKey(); Object val = entry.getValue(); res.put(deepClone(key, null), deepClone(val, null)); } return res; } else if (obj instanceof CacheWrapper) { CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj; CacheWrapper<Object> res = new CacheWrapper<Object>(); res.setExpire(wrapper.getExpire()); res.setLastLoadTime(wrapper.getLastLoadTime()); res.setCacheObject(deepClone(wrapper.getCacheObject(), null)); return res; } else { String json = MAPPER.writeValueAsString(obj); return MAPPER.readValue(json, clazz); }
850
528
712
1,240
54
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jdk/src/main/java/com/jarvis/cache/serializer/JdkSerializer.java
JdkSerializer
deepCloneMethodArgs
class JdkSerializer implements ISerializer<Object> { @Override public Object deserialize(byte[] bytes, Type returnType) throws Exception { if (null == bytes || bytes.length == 0) { return null; } ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInputStream input = new ObjectInputStream(inputStream); return input.readObject(); } @Override public byte[] serialize(Object obj) throws Exception { if (obj == null) { return new byte[0]; } // 将对象写到流里 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream output = new ObjectOutputStream(outputStream); output.writeObject(obj); output.flush(); return outputStream.toByteArray(); } @Override public Object deepClone(Object obj, final Type type) throws Exception { if (null == obj) { return obj; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } return deserialize(serialize(obj), null); } @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Object[] res = new Object[args.length]; int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { res[i] = deepClone(args[i], null); } return res;
193
441
167
608
55
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-kryo/src/main/java/com/jarvis/cache/serializer/KryoSerializer.java
KryoSerializer
deepCloneMethodArgs
class KryoSerializer implements ISerializer<Object> { private static final Logger LOGGER = LoggerFactory.getLogger(KryoSerializer.class); private KryoContext kryoContext; private static final Logger logger = LoggerFactory.getLogger(KryoSerializer.class); public KryoSerializer() { this.kryoContext = DefaultKryoContext.newKryoContextFactory(kryo -> { kryo.register(CacheWrapper.class, new CacheWrapperSerializer()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("kryo register classes successfully."); } }); } /** * 添加Kryo类注册器 * @param registration see {@link KryoClassRegistration} */ public void addKryoClassRegistration(KryoClassRegistration registration) { kryoContext.addKryoClassRegistration(registration); } @Override public byte[] serialize(Object obj) throws Exception { if (obj == null) { return null; } return kryoContext.serialize(obj); } @Override public Object deserialize(byte[] bytes, Type returnType) throws Exception { if (null == bytes || bytes.length == 0) { return null; } return kryoContext.deserialize(bytes); } @Override public Object deepClone(Object obj, Type type) throws Exception { if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } return deserialize(serialize(obj), null); } @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Object[] res = new Object[args.length]; int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { res[i] = deepClone(args[i], null); } return res;
174
599
165
764
56
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-kryo/src/main/java/com/jarvis/cache/serializer/kryo/CacheWrapperSerializer.java
CacheWrapperSerializer
read
class CacheWrapperSerializer extends Serializer<CacheWrapper> { @Override @SuppressWarnings("unchecked") public void write(Kryo kryo, Output output, CacheWrapper object) { output.writeInt(object.getExpire(), true); output.writeLong(object.getLastLoadTime(), true); kryo.writeClassAndObject(output, object.getCacheObject()); } @Override @SuppressWarnings("unchecked") public CacheWrapper read(Kryo kryo, Input input, Class<CacheWrapper> type) {<FILL_FUNCTION_BODY>} }
int expire = input.readInt(true); long lastLoadTime = input.readLong(true); Object o = kryo.readClassAndObject(input); CacheWrapper cacheWrapper = new CacheWrapper(); cacheWrapper.setCacheObject(o); cacheWrapper.setExpire(expire); cacheWrapper.setLastLoadTime(lastLoadTime); return cacheWrapper;
83
161
100
261
57
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-kryo/src/main/java/com/jarvis/cache/serializer/kryo/DefaultKryoContext.java
DefaultKryoContext
deserialize
class DefaultKryoContext implements KryoContext { private static final int DEFAULT_BUFFER_SIZE = 1024 * 100; private KryoPool pool; private List<KryoClassRegistration> registrations; public static KryoContext newKryoContextFactory(KryoClassRegistration registration) { KryoContext kryoContext = new DefaultKryoContext(); kryoContext.addKryoClassRegistration(registration); return kryoContext; } private DefaultKryoContext() { registrations = new ArrayList<>(); //KryoFactory的create方法会延后调用 pool = new KryoPool.Builder(() -> { Kryo kryo = new Kryo(); registrations.forEach(reg -> reg.register(kryo)); return kryo; }).softReferences().build(); } @Override public byte[] serialize(Object obj) { return serialize(obj, DEFAULT_BUFFER_SIZE); } @Override public byte[] serialize(Object obj, int bufferSize) { Kryo kryo = pool.borrow(); try (Output output = new Output(new ByteArrayOutputStream(), bufferSize)) { kryo.writeClassAndObject(output, obj); return output.toBytes(); } finally { pool.release(kryo); } } @Override public Object deserialize(byte[] serialized) {<FILL_FUNCTION_BODY>} @Override public void addKryoClassRegistration(KryoClassRegistration registration) { if (null != registration) { registrations.add(registration); } } }
Kryo kryo = pool.borrow(); try (Input input = new Input(new ByteArrayInputStream(serialized))) { Object o = kryo.readClassAndObject(input); return o; } finally { pool.release(kryo); }
89
453
75
528
58
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/HeapByteBufUtil.java
HeapByteBufUtil
getLong
class HeapByteBufUtil { static byte getByte(byte[] memory, int index) { return memory[index]; } static short getShort(byte[] memory, int index) { return (short) (memory[index] << 8 | memory[index + 1] & 0xFF); } static short getShortLE(byte[] memory, int index) { return (short) (memory[index] & 0xff | memory[index + 1] << 8); } static int getUnsignedMedium(byte[] memory, int index) { return (memory[index] & 0xff) << 16 | (memory[index + 1] & 0xff) << 8 | memory[index + 2] & 0xff; } static int getUnsignedMediumLE(byte[] memory, int index) { return memory[index] & 0xff | (memory[index + 1] & 0xff) << 8 | (memory[index + 2] & 0xff) << 16; } static int getInt(byte[] memory, int index) { return (memory[index] & 0xff) << 24 | (memory[index + 1] & 0xff) << 16 | (memory[index + 2] & 0xff) << 8 | memory[index + 3] & 0xff; } static int getIntLE(byte[] memory, int index) { return memory[index] & 0xff | (memory[index + 1] & 0xff) << 8 | (memory[index + 2] & 0xff) << 16 | (memory[index + 3] & 0xff) << 24; } static long getLong(byte[] memory, int index) {<FILL_FUNCTION_BODY>} static long getLongLE(byte[] memory, int index) { return (long) memory[index] & 0xff | ((long) memory[index + 1] & 0xff) << 8 | ((long) memory[index + 2] & 0xff) << 16 | ((long) memory[index + 3] & 0xff) << 24 | ((long) memory[index + 4] & 0xff) << 32 | ((long) memory[index + 5] & 0xff) << 40 | ((long) memory[index + 6] & 0xff) << 48 | ((long) memory[index + 7] & 0xff) << 56; } static void setByte(byte[] memory, int index, int value) { memory[index] = (byte) value; } static void setShort(byte[] memory, int index, int value) { memory[index] = (byte) (value >>> 8); memory[index + 1] = (byte) value; } static void setShortLE(byte[] memory, int index, int value) { memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); } static void setMedium(byte[] memory, int index, int value) { memory[index] = (byte) (value >>> 16); memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) value; } static void setMediumLE(byte[] memory, int index, int value) { memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) (value >>> 16); } static void setInt(byte[] memory, int index, int value) { memory[index] = (byte) (value >>> 24); memory[index + 1] = (byte) (value >>> 16); memory[index + 2] = (byte) (value >>> 8); memory[index + 3] = (byte) value; } static void setIntLE(byte[] memory, int index, int value) { memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) (value >>> 16); memory[index + 3] = (byte) (value >>> 24); } static void setLong(byte[] memory, int index, long value) { memory[index] = (byte) (value >>> 56); memory[index + 1] = (byte) (value >>> 48); memory[index + 2] = (byte) (value >>> 40); memory[index + 3] = (byte) (value >>> 32); memory[index + 4] = (byte) (value >>> 24); memory[index + 5] = (byte) (value >>> 16); memory[index + 6] = (byte) (value >>> 8); memory[index + 7] = (byte) value; } static void setLongLE(byte[] memory, int index, long value) { memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) (value >>> 16); memory[index + 3] = (byte) (value >>> 24); memory[index + 4] = (byte) (value >>> 32); memory[index + 5] = (byte) (value >>> 40); memory[index + 6] = (byte) (value >>> 48); memory[index + 7] = (byte) (value >>> 56); } private HeapByteBufUtil() { } }
return ((long) memory[index] & 0xff) << 56 | ((long) memory[index + 1] & 0xff) << 48 | ((long) memory[index + 2] & 0xff) << 40 | ((long) memory[index + 3] & 0xff) << 32 | ((long) memory[index + 4] & 0xff) << 24 | ((long) memory[index + 5] & 0xff) << 16 | ((long) memory[index + 6] & 0xff) << 8 | (long) memory[index + 7] & 0xff;
185
1,499
165
1,664
59
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/ProtoBufSerializer.java
ProtoBufSerializer
deepClone
class ProtoBufSerializer implements ISerializer<CacheWrapper<Object>> { private ConcurrentHashMap<Class, Lambda> lambdaMap = new ConcurrentHashMap<>(); private static final ObjectMapper MAPPER = new ObjectMapper(); public ProtoBufSerializer() { MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MAPPER.registerModule(new SimpleModule().addSerializer(new NullValueSerializer(null))); MAPPER.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); } @Override public byte[] serialize(CacheWrapper<Object> obj) throws Exception { WriteByteBuf byteBuf = new WriteByteBuf(); byteBuf.writeInt(obj.getExpire()); byteBuf.writeLong(obj.getLastLoadTime()); Object cacheObj = obj.getCacheObject(); if (cacheObj != null) { if (cacheObj instanceof Message) { byteBuf.writeBytes(((Message) cacheObj).toByteArray()); } else { MAPPER.writeValue(byteBuf, cacheObj); } } return byteBuf.toByteArray(); } @Override public CacheWrapper<Object> deserialize(final byte[] bytes, Type returnType) throws Exception { if (bytes == null || bytes.length == 0) { return null; } CacheWrapper<Object> cacheWrapper = new CacheWrapper<>(); ReadByteBuf byteBuf = new ReadByteBuf(bytes); cacheWrapper.setExpire(byteBuf.readInt()); cacheWrapper.setLastLoadTime(byteBuf.readLong()); byte[] body = byteBuf.readableBytes(); if (body == null || body.length == 0) { return cacheWrapper; } Class<?> clazz = TypeFactory.rawClass(returnType); if (Message.class.isAssignableFrom(clazz)) { Lambda lambda = getLambda(clazz); Object obj = lambda.invoke_for_Object(new ByteArrayInputStream(body)); cacheWrapper.setCacheObject(obj); } else { Type[] agsType = new Type[]{returnType}; JavaType javaType = MAPPER.getTypeFactory().constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null)); cacheWrapper.setCacheObject(MAPPER.readValue(body, clazz)); } return cacheWrapper; } @SuppressWarnings("unchecked") @Override public Object deepClone(Object obj, Type type) throws Exception {<FILL_FUNCTION_BODY>} @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception { if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Object[] res = new Object[args.length]; int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { res[i] = deepClone(args[i], null); } return res; } @SuppressWarnings("unchecked") private Lambda getLambda(Class clazz) throws NoSuchMethodException { Lambda lambda = lambdaMap.get(clazz); if (lambda == null) { Method method = clazz.getDeclaredMethod("parseFrom", InputStream.class); try { lambda = LambdaFactory.create(method); lambdaMap.put(clazz, lambda); } catch (Throwable throwable) { throwable.printStackTrace(); } } return lambda; } private class NullValueSerializer extends StdSerializer<NullValue> { private static final long serialVersionUID = 1999052150548658808L; private final String classIdentifier; /** * @param classIdentifier can be {@literal null} and will be defaulted * to {@code @class}. */ NullValueSerializer(String classIdentifier) { super(NullValue.class); this.classIdentifier = StringUtil.hasText(classIdentifier) ? classIdentifier : "@class"; } /* * (non-Javadoc) * @see * com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java. * lang.Object, com.fasterxml.jackson.core.JsonGenerator, * com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeStringField(classIdentifier, NullValue.class.getName()); jgen.writeEndObject(); } } }
if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } if (obj instanceof CacheWrapper) { CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj; CacheWrapper<Object> res = new CacheWrapper<>(); res.setExpire(wrapper.getExpire()); res.setLastLoadTime(wrapper.getLastLoadTime()); res.setCacheObject(deepClone(wrapper.getCacheObject(), null)); return res; } if (obj instanceof Message) { return ((Message) obj).toBuilder().build(); } return MAPPER.readValue(MAPPER.writeValueAsBytes(obj), clazz);
341
1,320
311
1,631
60
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/ReadByteBuf.java
ReadByteBuf
readableBytes
class ReadByteBuf { private byte[] array; private int readerIndex; public ReadByteBuf(byte[] array) { this.array = array; this.readerIndex = 0; } public byte readByte() { byte value = HeapByteBufUtil.getByte(array, readerIndex); readerIndex += 1; return value; } public int readInt() { int value = HeapByteBufUtil.getInt(array, readerIndex); readerIndex += 4; return value; } public long readLong() { long value = HeapByteBufUtil.getLong(array, readerIndex); readerIndex += 8; return value; } public byte[] readableBytes() {<FILL_FUNCTION_BODY>} }
byte[] newArray = new byte[array.length - readerIndex]; System.arraycopy(array, readerIndex, newArray, 0, newArray.length); return newArray;
40
209
49
258
61
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/WriteByteBuf.java
WriteByteBuf
grow
class WriteByteBuf extends OutputStream { private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private byte[] buf; private int count; public WriteByteBuf() { this(32); } @Override public void write(int b) throws IOException { writeByte((byte) b); } public WriteByteBuf(int arrayLength) { buf = new byte[arrayLength]; } public void writeByte(byte value) { int length = 1; ensureCapacity(length + count); HeapByteBufUtil.setByte(buf, count, value); count += length; } public void writeInt(int value) { int length = 4; ensureCapacity(length + count); HeapByteBufUtil.setInt(buf, count, value); count += length; } public void writeLong(long value) { int length = 8; ensureCapacity(length + count); HeapByteBufUtil.setLong(buf, count, value); count += length; } public void writeBytes(byte[] bytes) { int length = bytes.length; ensureCapacity(bytes.length + count); System.arraycopy(bytes, 0, buf, count, length); count += bytes.length; } public byte[] toByteArray() { byte[] newArray = new byte[count]; System.arraycopy(buf, 0, newArray, 0, count); return newArray; } private void ensureCapacity(int minCapacity) { // overflow-conscious code if (minCapacity - buf.length > 0) grow(minCapacity); } private void grow(int minCapacity) {<FILL_FUNCTION_BODY>} private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } }
// overflow-conscious code int oldCapacity = buf.length; int newCapacity = oldCapacity << 1; if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); buf = Arrays.copyOf(buf, newCapacity);
104
552
105
657
62
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/admin/AutoloadCacheController.java
AutoloadCacheController
listAutoLoadVO
class AutoloadCacheController { private static final Logger log = LoggerFactory.getLogger(AutoloadCacheController.class); private final CacheHandler autoloadCacheHandler; public AutoloadCacheController(CacheHandler autoloadCacheHandler) { this.autoloadCacheHandler = autoloadCacheHandler; } @GetMapping public AutoLoadVO[] listAutoLoadVO() {<FILL_FUNCTION_BODY>} @GetMapping("/args") public Object[] showArgs(String key, String hfield) { CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield); AutoLoadTO tmpTO = autoloadCacheHandler.getAutoLoadHandler().getAutoLoadTO(cacheKeyTO); if (null != tmpTO && null != tmpTO.getArgs()) { return tmpTO.getArgs(); } return null; } @PostMapping("removeCache") public boolean removeCache(String key, String hfield) { CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield); try { Set<CacheKeyTO> keys=new HashSet<>(); keys.add(cacheKeyTO); autoloadCacheHandler.delete(keys); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } @PostMapping("removeAutoloadTO") public boolean removeAutoloadTO(String key, String hfield) { CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield); try { autoloadCacheHandler.getAutoLoadHandler().removeAutoLoadTO(cacheKeyTO); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } @PostMapping("resetLastLoadTime") public boolean resetLastLoadTime(String key, String hfield) { CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield); try { autoloadCacheHandler.getAutoLoadHandler().resetAutoLoadLastLoadTime(cacheKeyTO); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } private static final ThreadLocal<SimpleDateFormat> FORMATER = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; private String formatDate(long time) { if (time < 100000) { return ""; } Date date = new Date(time); return FORMATER.get().format(date); } }
AutoLoadTO queue[] = autoloadCacheHandler.getAutoLoadHandler().getAutoLoadQueue(); if (null == queue || queue.length == 0) { return null; } AutoLoadVO[] autoLoadVOs = new AutoLoadVO[queue.length]; for (int i = 0; i < queue.length; i++) { AutoLoadTO tmpTO = queue[i]; CacheAopProxyChain pjp = tmpTO.getJoinPoint(); String className = pjp.getTarget().getClass().getName(); String methodName = pjp.getMethod().getName(); CacheKeyTO cacheKeyTO = tmpTO.getCacheKey(); AutoLoadVO autoLoadVO = new AutoLoadVO(); autoLoadVO.setNamespace(cacheKeyTO.getNamespace()); autoLoadVO.setKey(cacheKeyTO.getKey()); autoLoadVO.setHfield(cacheKeyTO.getHfield()); autoLoadVO.setMethod(className + "." + methodName); autoLoadVO.setLastRequestTime(formatDate(tmpTO.getLastRequestTime())); autoLoadVO.setFirstRequestTime(formatDate(tmpTO.getFirstRequestTime())); autoLoadVO.setRequestTimes(tmpTO.getRequestTimes()); autoLoadVO.setLastLoadTime(formatDate(tmpTO.getLastLoadTime())); autoLoadVO.setExpire(tmpTO.getCache().expire()); // 缓存过期时间 autoLoadVO.setExpireTime(formatDate(tmpTO.getLastLoadTime() + tmpTO.getCache().expire() * 1000)); autoLoadVO.setRequestTimeout(tmpTO.getCache().requestTimeout()); autoLoadVO.setRequestTimeoutTime( formatDate(tmpTO.getLastRequestTime() + tmpTO.getCache().requestTimeout() * 1000)); autoLoadVO.setLoadCount(tmpTO.getLoadCnt()); autoLoadVO.setAverageUseTime(tmpTO.getAverageUseTime()); autoLoadVOs[i] = autoLoadVO; } return autoLoadVOs;
417
765
523
1,288
63
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/admin/HTTPBasicAuthorizeAttribute.java
HTTPBasicAuthorizeAttribute
checkHeaderAuth
class HTTPBasicAuthorizeAttribute implements Filter { private static final String SESSION_AUTH_ATTRIBUTE = "autoload-cache-auth"; private final AutoloadCacheProperties properties; public HTTPBasicAuthorizeAttribute(AutoloadCacheProperties properties) { this.properties = properties; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String sessionAuth = (String) (request).getSession().getAttribute(SESSION_AUTH_ATTRIBUTE); if (sessionAuth == null) { if (!checkHeaderAuth(request, response)) { response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setHeader("WWW-Authenticate", "Basic realm=\"input username and password\""); return; } } chain.doFilter(request, response); } private boolean checkHeaderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>} private String getFromBASE64(String s) { if (s == null) { return null; } try { byte[] b = Base64.getDecoder().decode(s); return new String(b); } catch (Exception e) { return null; } } @Override public void destroy() { } }
String userName = properties.getAdminUserName(); if (null == userName || userName.isEmpty()) { return true; } String password = properties.getAdminPassword(); String auth = request.getHeader("Authorization"); if ((auth != null) && (auth.length() > 6)) { auth = auth.substring(6, auth.length()); String decodedAuth = getFromBASE64(auth); if (decodedAuth != null) { String[] userArray = decodedAuth.split(":"); if (userArray != null && userArray.length == 2 && userName.equals(userArray[0])) { if ((null == password || password.isEmpty()) || (null != password && password.equals(userArray[1]))) { request.getSession().setAttribute(SESSION_AUTH_ATTRIBUTE, decodedAuth); return true; } } } } return false;
354
448
244
692
64
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/autoconfigure/AutoloadCacheAutoConfigure.java
AutoloadCacheAutoConfigure
filterRegistrationBean
class AutoloadCacheAutoConfigure { private static final String VALIDATOR_BEAN_NAME = "autoloadCacheAutoConfigurationValidator"; @Autowired private AutoloadCacheProperties config; private final ILock lock; public AutoloadCacheAutoConfigure(ObjectProvider<ILock> lockProvider) { if (null != lockProvider) { lock = lockProvider.getIfAvailable(); } else { lock = null; } } @Bean(name = VALIDATOR_BEAN_NAME) public CacheManagerValidator autoloadCacheAutoConfigurationValidator() { return new CacheManagerValidator(); } @Bean(destroyMethod = "destroy") @ConditionalOnMissingBean(CacheHandler.class) @ConditionalOnBean({ ICacheManager.class, AbstractScriptParser.class, ICloner.class }) public CacheHandler autoloadCacheHandler(ICacheManager cacheManager, AbstractScriptParser scriptParser, ICloner cloner) { CacheHandler cacheHandler = new CacheHandler(cacheManager, scriptParser, config.getConfig(), cloner); cacheHandler.setLock(lock); return cacheHandler; } // 1. 创建通知 suixingpay.autoload.cache. 和 // suixingpay.autoload.cache.enable-delete @Bean @ConditionalOnBean(CacheHandler.class) @ConditionalOnProperty(value = AutoloadCacheProperties.PREFIX + ".enable-read-and-write", matchIfMissing = true) public CacheMethodInterceptor autoloadCacheMethodInterceptor(CacheHandler cacheHandler) { return new CacheMethodInterceptor(cacheHandler, config); } @Bean @ConditionalOnBean(CacheHandler.class) @ConditionalOnProperty(value = AutoloadCacheProperties.PREFIX + ".enable-delete", matchIfMissing = true) public CacheDeleteInterceptor autoloadCacheDeleteInterceptor(CacheHandler cacheHandler) { return new CacheDeleteInterceptor(cacheHandler, config); } @Bean @ConditionalOnBean(CacheHandler.class) @ConditionalOnProperty(value = AutoloadCacheProperties.PREFIX + ".enable-delete", matchIfMissing = true) public CacheDeleteTransactionalInterceptor autoloadCacheDeleteTransactionalInterceptor(CacheHandler cacheHandler) { return new CacheDeleteTransactionalInterceptor(cacheHandler, config); } // 2.配置Advisor @Bean("autoloadCacheAdvisor") @ConditionalOnBean(CacheMethodInterceptor.class) public AbstractPointcutAdvisor autoloadCacheAdvisor(CacheMethodInterceptor cacheMethodInterceptor) { AbstractPointcutAdvisor cacheAdvisor = new MethodAnnotationPointcutAdvisor(Cache.class, cacheMethodInterceptor); cacheAdvisor.setOrder(config.getCacheOrder()); return cacheAdvisor; } @Bean("autoloadCacheDeleteAdvisor") @ConditionalOnBean(CacheDeleteInterceptor.class) public AbstractPointcutAdvisor autoloadCacheDeleteAdvisor(CacheDeleteInterceptor cacheDeleteInterceptor) { AbstractPointcutAdvisor cacheDeleteAdvisor = new MethodAnnotationPointcutAdvisor(CacheDelete.class, cacheDeleteInterceptor); cacheDeleteAdvisor.setOrder(config.getDeleteCacheOrder()); return cacheDeleteAdvisor; } @Bean("autoloadCacheDeleteTransactionalAdvisor") @ConditionalOnBean(CacheDeleteTransactionalInterceptor.class) public AbstractPointcutAdvisor autoloadCacheDeleteTransactionalAdvisor( CacheDeleteTransactionalInterceptor cacheDeleteTransactionalInterceptor) { AbstractPointcutAdvisor cacheDeleteTransactionalAdvisor = new MethodAnnotationPointcutAdvisor( CacheDeleteTransactional.class, cacheDeleteTransactionalInterceptor); cacheDeleteTransactionalAdvisor.setOrder(config.getDeleteCacheTransactionalOrder()); return cacheDeleteTransactionalAdvisor; } // 3.配置ProxyCreator @Bean @ConditionalOnBean(CacheHandler.class) public AbstractAdvisorAutoProxyCreator autoloadCacheAutoProxyCreator() { DefaultAdvisorAutoProxyCreator proxy = new DefaultAdvisorAutoProxyCreator(); proxy.setAdvisorBeanNamePrefix("autoloadCache"); proxy.setProxyTargetClass(config.isProxyTargetClass()); // proxy.setInterceptorNames("cacheAdvisor","cacheDeleteAdvisor","cacheDeleteTransactionalAdvisor");// // 注意此处不需要设置,否则会执行两次 return proxy; } @Bean @ConditionalOnWebApplication public FilterRegistrationBean filterRegistrationBean() {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnWebApplication @ConditionalOnMissingBean(AutoloadCacheController.class) public AutoloadCacheController AutoloadCacheController(CacheHandler autoloadCacheHandler) { return new AutoloadCacheController(autoloadCacheHandler); } static class CacheManagerValidator { @Autowired(required = false) private AbstractScriptParser scriptParser; @Autowired(required = false) private ISerializer<Object> serializer; @Autowired(required = false) private ICacheManager cacheManager; @PostConstruct public void checkHasCacheManager() { Assert.notNull(this.scriptParser, "No script parser could be auto-configured"); Assert.notNull(this.serializer, "No serializer could be auto-configured"); Assert.notNull(this.cacheManager, "No cache manager could be auto-configured"); } } }
FilterRegistrationBean registrationBean = new FilterRegistrationBean(); HTTPBasicAuthorizeAttribute httpBasicFilter = new HTTPBasicAuthorizeAttribute(config); registrationBean.setFilter(httpBasicFilter); List<String> urlPatterns = new ArrayList<String>(); urlPatterns.add("/autoload-cache-ui.html"); urlPatterns.add("/autoload-cache/*"); registrationBean.setUrlPatterns(urlPatterns); return registrationBean;
82
1,450
119
1,569
65
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/autoconfigure/AutoloadCacheManageConfiguration.java
LettuceCacheCacheManagerConfiguration
createRedisCacheManager
class LettuceCacheCacheManagerConfiguration { /** * 默认只支持{@link LettuceRedisClusterCacheManager}<br> * * @param config * @param serializer * @param connectionFactory * @return */ @Bean @ConditionalOnMissingBean(ICacheManager.class) @ConditionalOnBean(LettuceConnectionFactory.class) public ICacheManager autoloadCacheCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer, LettuceConnectionFactory connectionFactory) { return createRedisCacheManager(config, serializer, connectionFactory); } private ICacheManager createRedisCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer, LettuceConnectionFactory connectionFactory) {<FILL_FUNCTION_BODY>} }
RedisConnection redisConnection = null; try { redisConnection = connectionFactory.getConnection(); AbstractRedisCacheManager cacheManager = null; if (redisConnection instanceof LettuceClusterConnection) { LettuceClusterConnection lettuceClusterConnection = (LettuceClusterConnection) redisConnection; try { Field clusterClientField = LettuceClusterConnection.class.getDeclaredField("clusterClient"); clusterClientField.setAccessible(true); RedisClusterClient redisClusterClient = (RedisClusterClient) clusterClientField.get(lettuceClusterConnection); cacheManager = new LettuceRedisClusterCacheManager(redisClusterClient, serializer); } catch (Exception e) { log.error(e.getMessage(), e); } } else { cacheManager = new SpringRedisCacheManager(connectionFactory, serializer); } // 根据需要自行配置 cacheManager.setHashExpire(config.getJedis().getHashExpire()); return cacheManager; } catch (Throwable e) { log.error(e.getMessage(), e); throw e; } finally { RedisConnectionUtils.releaseConnection(redisConnection, connectionFactory); }
516
214
309
523

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
5
Add dataset card