当前位置: 代码迷 >> Web前端 >> 利用jdk动态署理
  详细解决方案

利用jdk动态署理

热度:159   发布时间:2012-07-01 13:15:00.0
利用jdk动态代理
业务接口
  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);
}
  相关解决方案