⽆处不在的代理模式(一)
一:动态代理介绍
1、增强型代理
(1)⽤户画像,收集⽤户⾏为⽇志
⽤户画像,需要收集"登陆"、"下单"、"评论"、"退货"等⾏为⽇志。然后在通过⼤数据引擎进
⾏分析画像。我们不能为每⼀个⽅法,增加采集⽇志。⼯作量实在是太⼤了。这时就可以给这
些⽅法进⾏“代理开光”,好处是核⼼功能不变,增加附加功能,并保留原有使⽤⽅式。
(2)Spring 声明示事务
我们所熟知的spring声明示事务就是⼀个典型的增强型代理,原本核⼼功能是做⼀些业务上的
增删改查,通过代理增强之后就多出⼀个事物的功能。但我们对原来服务的调⽤⽅式是保持不
变。
(3)增强代理的应⽤条件:
a. 普适性:代理逻辑能够适应⽤系统中的⼤部分场景
b. 业务⽆关性:不能影响业务,更不能够直接偶和业务。⽆论成功失败都不⼲涉现有业务。
强调这两个特性是有原因的。因为代理本身会提⾼系统的复杂度,使源码阅读和调试都会变得
困难,若不满⾜这两个条件复杂度会进⼀步上升。得不尝失,检芝麻丢⻄⽠。
⽐如上述关于Spring 声明示事务的例⼦,如果让你去调试关于事务相关的逻辑,根本就不知
道从哪⾥下⼿。所以当业务逻辑嵌⼊到代理中,这是⼀件⾮常可怕事情。
(4)总结:
增强型代理就是对已有的对像进⾏代理增强,好处是可⼤范围的覆盖。但坏处是它会给系统带
来复杂性,所以必须保证增强的逻辑是普适的,⽽且与业务⽆关。
二、动态代理的本质(深入分析JDK动态代理为什么只能使用接口)
public class UserServiceProxy implements InvocationHandler{ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 代理逻辑 或业务逻辑了 System.out.println("执行方法:"+method.getName()); return null; } public static void main(String[] args) throws IOException { // createProxyClass(); ClassLoader loader=UserService.class.getClassLoader();//对应被代理的类的加载器,确保使用同一个类来加载被代理类 InvocationHandler handler=new UserServiceProxy();//代理执行器 UserService service = (UserService) Proxy. newProxyInstance(loader, new Class[]{UserService.class}, handler);//生成代理类 new Class[]{UserService.class}要代理的接口集 service.editName(1,""); createProxyClass(); } // Class 获取proxy$1 代理实现的代码 通过反编译 public static void createProxyClass() throws IOException { byte[] bytes = ProxyGenerator.generateProxyClass("Proxy$1", new Class[]{UserService.class});//动态代理会调用该方法,生成被代理对象的字节码 Files.write(new File(System.getProperty("user.dir") + "/target/Proxy$1.class").toPath(), bytes); }}
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // import com.code.read.pattern.proxy.UserService; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; //继承proxy,实现被代理类。。反编译字节码得到 public final class Proxy$1 extends Proxy implements UserService { private static Method m1; private static Method m2; private static Method m3; private static Method m4; private static Method m0; public Proxy$1(InvocationHandler var1) throws { super(var1); } public final boolean equals(Object var1) throws { try { return (Boolean)super.h.invoke(this, m1, new Object[]{var1}); } catch (RuntimeException | Error var3) { throw var3; } catch (Throwable var4) { throw new UndeclaredThrowableException(var4); } } public final String toString() throws { try { return (String)super.h.invoke(this, m2, (Object[])null); } catch (RuntimeException | Error var2) { throw var2; } catch (Throwable var3) { throw new UndeclaredThrowableException(var3); } } public final String getName(Integer var1) throws { try { return (String)super.h.invoke(this, m3, new Object[]{var1}); } catch (RuntimeException | Error var3) { throw var3; } catch (Throwable var4) { throw new UndeclaredThrowableException(var4); } } //代理方法 public final void editName(Integer var1, String var2) throws { try { super.h.invoke(this, m4, new Object[]{var1, var2}); } catch (RuntimeException | Error var4) { throw var4; } catch (Throwable var5) { throw new UndeclaredThrowableException(var5); } } public final int hashCode() throws { try { return (Integer)super.h.invoke(this, m0, (Object[])null); } catch (RuntimeException | Error var2) { throw var2; } catch (Throwable var3) { throw new UndeclaredThrowableException(var3); } } static { try { m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object")); m2 = Class.forName("java.lang.Object").getMethod("toString"); m3 = Class.forName("com.code.read.pattern.proxy.UserService").getMethod("getName", Class.forName("java.lang.Integer")); m4 = Class.forName("com.code.read.pattern.proxy.UserService").getMethod("editName", Class.forName("java.lang.Integer"), Class.forName("java.lang.String")); m0 = Class.forName("java.lang.Object").getMethod("hashCode"); } catch (NoSuchMethodException var2) { throw new NoSuchMethodError(var2.getMessage()); } catch (ClassNotFoundException var3) { throw new NoClassDefFoundError(var3.getMessage()); } } }
动态⽣成的这个代理实例,实现了代理接⼝(UserService),⽤户可以直接调⽤接⼝中的⽅法。
最后逻辑将会交给代理执⾏器的invoke⽅法。这是如何实现的呢?
从图中可以看出代理实现中的每⼀个⽅法都会转调⽤,代理执⾏器中invoke⽅法。由此可以推
断出,代理执⾏器是代理实例中的⼀个属性。然后当流程到达代理执⾏器之后便就可以⾃定义
处理相关代理逻辑了。
其中代理实现部分的代码是看不到的.
通过反编译可以看出:
public Proxy$1(InvocationHandler var1) throws { super(var1); }//反编译可以看到,Proxy$1的构造方法,先去调用自己的父类Proxy的构造方法。 //Proxy的源码中的构造方法,InvocationHandler就是代理执行器
protected InvocationHandler h;//proxy持有代理执行器,因此最终调用到了invoke方法。也就是 super.h.invoke()
protected Proxy(InvocationHandler h) { Objects.requireNonNull(h); this.h = h; }
我们通过反编译出代码可以清楚看到Proxy$1对象持有一个InvocationHandler 代理执行器对象,由于Proxy$1继承自proxy代理,所以Proxy$1进行构造器构造时,会调用父类proxy的构造器,传入InvocationHandler对象,此时Proxy$1拥有了userService方法(实现了userService接口),拥有的InvocationHandler方法。所以当调用editmane时,就可以调用到invoke方法。
接着来看看,代理对象service是如何生成的。
UserService service = (UserService) Proxy.
newProxyInstance(loader, new Class[]{UserService.class}, handler);//生成代理类 new Class[]{UserService.class}要代理的接口集
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { Objects.requireNonNull(h); final Class<?>[] intfs = interfaces.clone();//克隆接口 final SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkProxyAccess(Reflection.getCallerClass(), loader, intfs); } /* * Look up or generate the designated proxy class. *///生成代理类,底层通过拼装class字节码的方式得到类 Class<?> cl = getProxyClass0(loader, intfs); /* * Invoke its constructor with the designated invocation handler. */ try { if (sm != null) { checkNewProxyPermission(Reflection.getCallerClass(), cl); } final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { cons.setAccessible(true); return null; } }); }//创建一个代理类是实例。调用代理类的构造器,构造器参数为InvocationHandler的接口实现类 return cons.newInstance(new Object[]{h}); } catch (IllegalAccessException|InstantiationException e) { throw new InternalError(e.toString(), e); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw new InternalError(t.toString(), t); } } catch (NoSuchMethodException e) { throw new InternalError(e.toString(), e); } }
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) { if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); }//校验 // If the proxy class defined by the given loader implementing // the given interfaces exists, this will simply return the cached copy; // otherwise, it will create the proxy class via the ProxyClassFactory //可以看到是从缓存中获取的代理类,该类通过工厂方法获取 return proxyClassCache.get(loader, interfaces); }
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>//代理类的缓存,当缓存存在直接直接获取,当缓存不存在调用ProxyClassFactory的apply方法来生成一个代理类 proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory()); /** * the invocation handler for this proxy instance. * @serial */ protected InvocationHandler h; /** * Prohibits instantiation. */ private Proxy() { }
private static final class ProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>> { // prefix for all proxy class names private static final String proxyClassNamePrefix = "$Proxy"; // next number to use for generation of unique proxy class names private static final AtomicLong nextUniqueNumber = new AtomicLong(); @Override //不存在时调用apply方法,生成代理类 public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) { Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length); for (Class<?> intf : interfaces) { /* * Verify that the class loader resolves the name of this * interface to the same Class object. */ Class<?> interfaceClass = null; try {//此处校验类加载器是否正确,如果类加载器不正确,则nterfaceClass != intf,加载的类不可能相等 interfaceClass = Class.forName(intf.getName(), false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != intf) { throw new IllegalArgumentException( intf + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. */ if (!interfaceClass.isInterface()) { throw new IllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. */ //判断该接口是否已经加入缓存 if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { throw new IllegalArgumentException( "repeated interface: " + interfaceClass.getName()); } } String proxyPkg = null; // package to define proxy class in int accessFlags = Modifier.PUBLIC | Modifier.FINAL; /* * Record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. Verify that * all non-public proxy interfaces are in the same package. */ for (Class<?> intf : interfaces) { int flags = intf.getModifiers(); if (!Modifier.isPublic(flags)) { accessFlags = Modifier.FINAL; String name = intf.getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } else if (!pkg.equals(proxyPkg)) { throw new IllegalArgumentException( "non-public interfaces from different packages"); } } } if (proxyPkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; } /* * Choose a name for the proxy class to generate. */ long num = nextUniqueNumber.getAndIncrement(); String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * Generate the specified proxy class. */ //生成代理类二进制字节码,ProxyGenerator.generateProxyClass生成.class文件的过程其实就是根据.class文件格式来一步步拼接处对应字节数组。
//由于一个Class包含一个类的所有完整信息,所以可以通过interfaces构建出一个字节码文件。
byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try {//装载到虚拟机中 return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { /* * A ClassFormatError here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded). */ throw new IllegalArgumentException(e.toString()); } } }
最终返回一个代理类,由于代理类持有一个代理执行器,所以,代理类反射创建一个代理对象userService。