-
代理服务工厂 /** * <h1>代理服务工厂</h1> * * @author: dengyw * @date: 2020/5/13 14:47 */
public final class ServiceProxyFactory { /** * <h1>获取缓存服务代理</h1> * @param object * @return T * @date 2020/5/20 16:43 * @author dengyw */ public final static <T> T getServiceProxy(Object object) throws Exception { InvocationHandler cacheServiceHandler = new ServiceCacheHandler(object); return (T) ProxyUtil.getProxyObject(object, cacheServiceHandler); } } - 代理服务处理类
/** * <h1>代理服务处理类</h1> * * @author: dengyw * @date: 2020/5/13 14:36 */ public class ServiceCacheHandler implements InvocationHandler { private transient static final Logger logger = LogManager.getLogger(ServiceCacheHandler.class); private final Object object; private final IInterceptor[] interceptors; public ServiceCacheHandler(Object object) { this.object = object; this.interceptors = ConfigFactory.INSTANCE.getConfig().getInterceptors(); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return invokeInterceptor(0, method, args); } private Object invokeInterceptor(int count, Method method, Object[] args) throws Exception { if(interceptors.length > count){ IInterceptor interceptor = interceptors[count]; try { interceptor.beforeInterceptor(this.object, method.getName(), args); if(logger.isDebugEnabled()){ logger.debug("invoke Interceptor:[" + interceptor.getClass().getName() + "]"); } Object result = invokeInterceptor(count + 1, method, args); interceptor.afterInterceptor(object, method.getName(), args, result); return result; } catch (Exception e){ interceptor.exceptionInterceptor(object, method.getName(), args, e); throw e; } } else { return method.invoke(object, args); } } }
- 获取代理服务工具类
/** * <h1>获取代理服务工具类</h1> * * @author: dengyw * @date: 2020/6/19 20:58 */
public final class ProxyUtil { private static final Map<Class<?>, Object> SERVICE_CACHE = new HashMap(); private ProxyUtil() { } public static final <T> T getProxyObject(T object, InvocationHandler serviceHandler) throws Exception { if(object instanceof Class){ throw new Exception("object:[" + object + "] not the instance."); } Class<?> clazz = object.getClass(); T proxyObject = (T) SERVICE_CACHE.get(clazz); if (proxyObject == null) { synchronized (SERVICE_CACHE) { proxyObject = (T) SERVICE_CACHE.get(clazz); if (proxyObject == null) { proxyObject = (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), serviceHandler); SERVICE_CACHE.put(clazz, proxyObject); } } } return proxyObject; } }