用例是实现脏字段跟踪器。为此我有一个界面:
public interface Dirtyable {
String ID = "dirty";
Set<String> getDirty();
static <T> T wrap(final T delegate) {
return DirtyableInterceptor.wrap(delegate, ReflectionUtils::getPropertyName);
}
static <T> T wrap(final T delegate, final Function<Method, String> resolver) {
return DirtyableInterceptor.wrap(delegate, resolver);
}
}
拦截器类中的包装方法是:
static <T> T wrap(final T delegate, final Function<Method, String> resolver) {
requireNonNull(delegate, "Delegate must be non-null");
requireNonNull(resolver, "Resolver must be non-null");
final Try<Class<T>> delegateClassTry = Try.of(() -> getClassForType(delegate.getClass()));
return delegateClassTry.flatMapTry(delegateClass ->
dirtyableFor(delegate, delegateClass, resolver))
.mapTry(Class::newInstance)
.getOrElseThrow(t -> new IllegalStateException(
"Could not wrap dirtyable for " + delegate.getClass(), t));
}
方法dirtyableFor
定义了一个ByteBuddy,它在每次调用时转发到一个特定的实例。然而,在每次调用时进行检测有点昂贵,因此它会缓存给定实例的类中的检测子类。为此,我使用 resilience4j
库(又名 javaslang-Circuitbreaker
)。
private static <T> Try<Class<? extends T>> dirtyableFor(final T delegate,
final Class<T> clazz,
final Function<Method, String> resolver) {
long start = System.currentTimeMillis();
Try<Class<? extends T>> r = Try.of(() -> ofCheckedSupplier(() ->
new ByteBuddy().subclass(clazz)
.defineField(Dirtyable.ID, Set.class, Visibility.PRIVATE)
.method(nameMatches("getDirty"))
.intercept(reference(new HashSet<>()))
.implement(Dirtyable.class)
.method(not(isDeclaredBy(Object.class))
.and(not(isAbstract()))
.and(isPublic()))
.intercept(withDefaultConfiguration()
.withBinders(Pipe.Binder.install(Function.class))
.to(new DirtyableInterceptor(delegate, resolver)))
.make().load(clazz.getClassLoader())
.getLoaded())
.withCache(getCache())
.decorate()
.apply(clazz));
System.out.println("Instrumentation time: " + (System.currentTimeMillis() - start));
return r;
}
private static <T> Cache<Class<? super T>, Class<T>> getCache() {
final CachingProvider provider = Caching.getCachingProvider();
final CacheManager manager = provider.getCacheManager();
final javax.cache.Cache<Class<? super T>, Class<T>> cache =
manager.getCache(Dirtyable.ID);
final Cache<Class<? super T>, Class<T>> dirtyCache = Cache.of(cache);
dirtyCache.getEventStream().map(Object::toString).subscribe(logger::debug);
return dirtyCache;
}
从日志来看,检测时间从缓存未命中的 70-100 毫秒下降到缓存命中的 0-2 毫秒。
为了完整起见,这里是拦截器方法:
@RuntimeType
@SuppressWarnings("unused")
public Object intercept(final @Origin Method method, final @This Dirtyable dirtyable,
final @Pipe Function<Object, Object> pipe) throws Throwable {
if (ReflectionUtils.isSetter(method)) {
final String property = resolver.apply(method);
dirtyable.getDirty().add(property);
logger.debug("Intercepted setter [{}], resolved property " +
"[{}] flagged as dirty.", method, property);
}
return pipe.apply(this.delegate);
}
此解决方案效果很好,只是 DirtyableInterceptor
对于缓存命中始终是相同的,因此委托(delegate)实例也是相同的。
是否可以将转发器绑定(bind)到实例的提供者,以便拦截的方法将转发给它?这怎么能做到呢?
最佳答案
您可以通过将 intercept
方法设置为 static
来创建无状态拦截器。要访问对象的状态,请在子类上定义两个字段,您可以在现在的静态拦截器中使用 @FieldValue
注释来访问这两个字段。您还需要使用 FieldAccessor
实现来读取值,而不是使用 FixedValue::reference
工具。您还需要使用 defineField
构建器方法定义字段。
您可以通过以下方式设置这些字段:
- 在
Dirtyable
接口(interface)中添加 setter 方法,并使用FieldAccessor
实现拦截它们。 - 定义您向其提供值的显式构造函数。这还允许您将字段定义为
final
。要实现构造函数,您首先需要调用 super 构造函数,然后多次调用FieldAccessor
来设置字段。
这样做,您已经创建了一个完全无状态的类,您可以重用该类,但需要初始化该类。 Byte Buddy 已经提供了内置的 TypeCache
以便于重用。
关于caching - 如何使用实例转发器缓存检测类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43784295/