hsf笔记-ProxyDecorator和ProxyFactor

2018-08-13  本文已影响44人  兴浩

参考:
https://blog.csdn.net/earthhour/article/details/53083597

1.ProxyDecorator

ProxyDecorator实现了一个service全局动态代理的接口

public interface ProxyDecorator {
    Class<?> decorate(ServiceMetadata var1);
}

2.ProxyDecoratorGenerator

根据ServiceMetadata信息返回每个ProxyDecorator中的装饰器接口

public class ProxyDecoratorGeneratorImpl implements ProxyDecoratorGenerator {
   
    private List<ProxyDecorator> proxyDecoratorPipe = HSFServiceContainer.getInstances(ProxyDecorator.class, new String[0]);

    public ProxyDecoratorGeneratorImpl() {
    }

    public Class<?>[] getDecorateInterfaces(ServiceMetadata serviceMetadata) {
        Class<?>[] result = new Class[0];
        if (serviceMetadata != null) {
            Set<Class<?>> decorateSet = new LinkedHashSet();
            Iterator i$ = this.proxyDecoratorPipe.iterator();

            while(i$.hasNext()) {
                ProxyDecorator proxyDecorator = (ProxyDecorator)i$.next();
                Class<?> decorate = proxyDecorator.decorate(serviceMetadata);
                if (decorate != null && decorate.isInterface()) {
                    decorateSet.add(decorate);
                }
            }
            result = (Class[])decorateSet.toArray(new Class[0]);
        }
        return result;
    }
}

Demo示例

public class ProxyDecoratorTest {

    @Test
    public void test1() {
        ProxyDecoratorGenerator service = HSFServiceContainer.getInstance(ProxyDecoratorGenerator.class);
        ServiceMetadata metadata=new ServiceMetadata(ApplicationModelFactory.getMainApplicationModel());
        Class<?>[] clsList=service.getDecorateInterfaces(metadata);
    }
}

3.ProxyFactory

在HSFApiConsumerBean初始化时,会为接口生成一个动态代理类, Proxy对象由ProxyFactory创建(https://www.jianshu.com/p/f67757927f0e)

生成代理对象流程

    private Object consume(ServiceMetadata metadata) {
        if (this.applicationModel.getConsumedServiceModel(metadata.getUniqueName()) != null) {
            return this.applicationModel.getConsumedServiceModel(metadata.getUniqueName()).getProxyObject();
        } else {
            ProxyDecoratorGenerator proxyDecoratorGenerator = (ProxyDecoratorGenerator)HSFServiceContainer.getInstance(ProxyDecoratorGenerator.class);
            Class<?>[] decorateInterfaces = proxyDecoratorGenerator.getDecorateInterfaces(metadata);
            ProxyFactory proxyFactory = (ProxyFactory)HSFServiceContainer.getInstance(ProxyFactory.class, metadata.getProxyStyle());
            Object proxy = proxyFactory.getProxy(metadata, decorateInterfaces);
            Method[] methods = proxyFactory.getMethods(proxy);
            ConsumerServiceModel consumerServiceModel = new ConsumerServiceModel(metadata, proxy, methods);
            metadata.setConsumerServiceModel(consumerServiceModel);
            this.applicationModel.initConsumerService(metadata.getUniqueName(), consumerServiceModel);
            metadata.referSync();
            return proxy;
        }
    }

JdkProxyFactory源码

public class JdkProxyFactory implements ProxyFactory {
    public JdkProxyFactory() {
    }

    public Object getProxy(ServiceMetadata metadata, Class... interfacesArray) {
        try {
            JdkProxyFactory.JdkProxyInvocationHandler jdkProxyInvocationHandler = new JdkProxyFactory.JdkProxyInvocationHandler(metadata);
            Object instance = Proxy.newProxyInstance(metadata.getIfClazz().getClassLoader(), interfacesArray, jdkProxyInvocationHandler);
            jdkProxyInvocationHandler.init(instance);
            return instance;
        } catch (Throwable var5) {
            throw new HSFException("failed to generate jdk proxy", var5);
        }
    }

    public Method[] getMethods(Object proxy) {
        try {
            Class<?> proxyClass = proxy.getClass();
            Method[] methods = new Method[proxyClass.getDeclaredFields().length];
            Field[] fields = proxyClass.getDeclaredFields();

            for(int i = 0; i < fields.length; ++i) {
                fields[i].setAccessible(true);
                methods[i] = (Method)fields[i].get(proxy);
            }

            return methods;
        } catch (Throwable var6) {
            throw new HSFException("failed to get jdk proxy methods", var6);
        }
    }

    private static class JdkProxyInvocationHandler extends ProxyInvocationHandler {
        private static final Logger LOGGER;
        private Method equalsMethod;
        private Method toStringMethod;
        private Method hashCodeMethod;

        public JdkProxyInvocationHandler(ServiceMetadata metadata) {
            super(metadata);
        }

        public void init(Object instance) {
            Method equalsMethod1 = null;
            Method toStringMethod1 = null;
            Method hashCodeMethod1 = null;

            try {
                Field hashCodeField = instance.getClass().getDeclaredField("m0");
                hashCodeField.setAccessible(true);
                hashCodeMethod1 = (Method)hashCodeField.get(instance);
                Field equalsField = instance.getClass().getDeclaredField("m1");
                equalsField.setAccessible(true);
                equalsMethod1 = (Method)equalsField.get(instance);
                Field toStringField = instance.getClass().getDeclaredField("m2");
                toStringField.setAccessible(true);
                toStringMethod1 = (Method)toStringField.get(instance);
            } catch (Exception var8) {
                String errorCodeStr = LoggerHelper.getErrorCodeStr("HSF", "HSF-0051", "HSF", "find proxy hashcode/equals/toString method got error");
                LOGGER.warn(errorCodeStr, var8);
            }

            this.hashCodeMethod = hashCodeMethod1;
            this.toStringMethod = toStringMethod1;
            this.equalsMethod = equalsMethod1;
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method == this.toStringMethod) {
                return this.serviceMetadata.getInterfaceName();
            } else if (method == this.equalsMethod) {
                return proxy == args[0];
            } else {
                return method == this.hashCodeMethod ? System.identityHashCode(proxy) : super.invoke(proxy, method, args);
            }
        }

        static {
            LOGGER = LoggerInit.LOGGER;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读