业务接口
public interface ForumService {
public void removeTopic(int topicId);
public void removeForum(int forumId);
}
性能监测
public class PerformanceHandler implements InvocationHandler{
private Object target ;
public PerformanceHandler(Object target){
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
PerformanceMonitor.begin(target.getClass().getName()+method.getName());
Object obj =method.invoke(target, args) ;
PerformanceMonitor.end();
return obj;
}
}
监测
public class PerformanceMonitor {
private static ThreadLocal<MethodPerformance> local = new ThreadLocal<MethodPerformance>();
public static void begin(String method){
System.out.println("begin monitor....");
MethodPerformance performace = new MethodPerformance(method);
local.set(performace);
}
public static void end(){
System.out.println("end monitor....");
MethodPerformance performace = local.get();
performace.printPerformance();
}
}
public class MethodPerformance {
private long begin;
private String serviceMethod;
private long end;
public MethodPerformance(String serviceMethod){
this.serviceMethod = serviceMethod;
begin = System.currentTimeMillis();
}
public void printPerformance(){
end = System.currentTimeMillis();
long elapse = end -begin;
System.out.println(serviceMethod+"花费了"+elapse);
}
}
实现接口类
public class ForumServiceImpl implements ForumService{
public void removeForum(int forumId) {
try{
Thread.sleep(20);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void removeTopic(int topicId) {
try{
Thread.sleep(50);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
测试
public static void test(){
ForumService target = new ForumServiceImpl();
PerformanceHandler pf = new PerformanceHandler(target);
ForumService proxy = (ForumService)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), pf);
proxy.removeForum(1);
proxy.removeTopic(2);
}