我正在尝试制作一个基本方面(主要是作为概念验证),我可以使用它来跟踪通过套接字完成的 IO。
以下代码使用基于 Commons-IO 的 CountingInputStream 包装从套接字获取输入流的任何调用。那部分有效。
什么不起作用(我怀疑这是因为我对切入点定义进行了修改)是从 CountingInputStream 中获取字节数。
关闭/重置建议永远不会被击中。(在将其切换到 @Around 之前,我将其作为 @Before 建议 - 但这也不起作用......)
(一旦我得到了基本的东西,我确实计划清理它一点)
package com.foo.io;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.commons.io.output.CountingOutputStream;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import java.io.*;
import java.net.Socket;
@Aspect
public class SocketStreamWrapper {
// can trivially create a map keeping track of bytes sent to / from a given address if this is desired
final Counter inboundByteCounter;
final Histogram inboundByteHistogram;
final Counter outboundByteCounter;
final Histogram outboundByteHistogram;
public SocketStreamWrapper() {
inboundByteCounter = Metrics.defaultRegistry().newCounter(new MetricName("inbound", "bytes", "counted"));
inboundByteHistogram = Metrics.defaultRegistry().newHistogram(new MetricName("inbound", "bytes", "histogram"), true);
outboundByteCounter = Metrics.defaultRegistry().newCounter(new MetricName("outbound", "bytes", "counted"));
outboundByteHistogram = Metrics.defaultRegistry().newHistogram(new MetricName("outbound", "bytes", "histogram"), true);
}
@Pointcut("call(* java.net.Socket.getInputStream()) && target(s)")
void input(Socket s) {
}
@Pointcut("call(* CountingInputStream.close()) && this(cis)")
void close(CountingInputStream cis) {
}
@Pointcut("call(* CountingInputStream.reset()) && this(cis)")
void reset(CountingInputStream cis) {
}
@Pointcut("call(* CountingInputStream+.read*()) && this(cis)")
void read(CountingInputStream cis) {
}
@Around("close(cis)")
public void closeCountingStream(ProceedingJoinPoint jp, CountingInputStream cis) throws Throwable {
inboundByteCounter.inc(cis.getByteCount());
inboundByteHistogram.update(cis.getByteCount());
cis.resetByteCount();
jp.proceed();
}
@Around("input(s)")
public Object wrapInputStream(ProceedingJoinPoint joinPoint,
Socket s)
throws Throwable {
InputStream in = (InputStream) joinPoint.proceed();
return new CountingInputStream(in);
}
@Pointcut("call(* java.net.Socket.getOutputStream()) && target(s)")
void output(Socket s) {
}
@Around("output(s)")
public Object wrapOutputStream(ProceedingJoinPoint joinPoint,
Socket s)
throws Throwable {
OutputStream out = (OutputStream) joinPoint.proceed();
return new CountingOutputStream(out);
}
}