Skip to content
Open

Aaaa #86

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 26 additions & 26 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -87,31 +87,31 @@
<argLine>-Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
<plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<configLocation>${basedir}/.circleci/checkstyle.xml</configLocation>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<enableRulesSummary>false</enableRulesSummary>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.29</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<configLocation>${basedir}/.circleci/checkstyle.xml</configLocation>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<enableRulesSummary>false</enableRulesSummary>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.29</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
</project>
4 changes: 4 additions & 0 deletions src/main/java/com/github/hcsp/annotation/Cache.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.github.hcsp.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Cache {
// 标记缓存的时长(秒),默认60s
int cacheSeconds() default 60;
Expand Down
109 changes: 108 additions & 1 deletion src/main/java/com/github/hcsp/annotation/CacheClassDecorator.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,130 @@
package com.github.hcsp.annotation;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.implementation.bind.annotation.This;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;

public class CacheClassDecorator {
// 将传入的服务类Class进行增强
// 使得返回一个具有如下功能的Class:
// 如果某个方法标注了@Cache注解,则返回值能够被自动缓存注解所指定的时长
// 这意味着,在短时间内调用同一个服务的同一个@Cache方法两次
// 它实际上只被调用一次,第二次的结果直接从缓存中获取
// 注意,缓存的实现需要是线程安全的
@SuppressWarnings("unchecked")
public static <T> Class<T> decorate(Class<T> klass) {
return klass;
return (Class<T>) new ByteBuddy()
// 对带有cache缓存的方法进行增强
.subclass(klass)
.method(ElementMatchers.isAnnotatedWith(Cache.class))
.intercept(MethodDelegation.to(CacheAdvisor.class))
.make()
.load(klass.getClassLoader())
.getLoaded();

}

private static class CacheKey {
private Object thisObject;
private String methodName;
private Object[] arguments;

CacheKey(Object thisObject, String methodName, Object[] arguments) {
this.thisObject = thisObject;
this.methodName = methodName;
this.arguments = arguments;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CacheKey cacheKey = (CacheKey) o;
return Objects.equals(thisObject, cacheKey.thisObject) &&
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'&&' 应另起一行。

Objects.equals(methodName, cacheKey.methodName) &&
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'&&' 应另起一行。

Arrays.equals(arguments, cacheKey.arguments);
}

@Override
public int hashCode() {
int result = Objects.hash(thisObject, methodName);
result = 31 * result + Arrays.hashCode(arguments);
return result;
}
}

private static class CacheValue {
private Object value;
private long time;

CacheValue(Object value, long time) {
this.value = value;
this.time = time;
}
}


public static class CacheAdvisor {
private static ConcurrentHashMap<CacheKey, CacheValue> cache = new ConcurrentHashMap<>();

@RuntimeType
public static Object cache(
@SuperCall Callable<Object> superCall,
@Origin Method method,
@This Object thisObject,
@AllArguments Object[] arguments) throws Exception {
CacheKey cacheKey = new CacheKey(thisObject, method.getName(), arguments);
final CacheValue resultExistInCache = cache.get(cacheKey);
if (resultExistInCache != null) {
if (cacheExpires(resultExistInCache, method)) {
return invokeRealMethodAndPutIntoCache(superCall, cacheKey);
} else {
return resultExistInCache.value;
}

} else {
return invokeRealMethodAndPutIntoCache(superCall, cacheKey);
}
}

private static Object invokeRealMethodAndPutIntoCache(@SuperCall Callable<Object> superCall, CacheKey cacheKey) throws Exception {
Object realMethodInvocationResult = superCall.call();
cache.put(cacheKey, new CacheValue(realMethodInvocationResult, System.currentTimeMillis()));
return realMethodInvocationResult;
}

private static boolean cacheExpires(CacheValue cacheValue, Method method) {
long time = cacheValue.time;
int cacheSeconds = method.getAnnotation(Cache.class).cacheSeconds();
return System.currentTimeMillis() - time > cacheSeconds * 1000;
}
}


public static void main(String[] args) throws Exception {
DataService dataService = decorate(DataService.class).getConstructor().newInstance();

// 有缓存的查询:只有第一次执行了真正的查询操作,第二次从缓存中获取
System.out.println(dataService.queryData(1));
Thread.sleep(1 * 1000);
System.out.println(dataService.queryData(1));
Thread.sleep(3 * 1000);
System.out.println(dataService.queryData(1));

// 无缓存的查询:两次都执行了真正的查询操作
System.out.println(dataService.queryDataWithoutCache(1));
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/github/hcsp/annotation/DataService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class DataService {
* @param id 数据ID
* @return 查询到的数据列表
*/
@Cache
@Cache(cacheSeconds = 2)
public List<Object> queryData(int id) {
// 模拟一个查询操作
Random random = new Random();
Expand Down