在使用了netty的系统中,有时会出现内存泄露的问题,我们就需要去监控这个堆外内存的占用,以排查是否是堆外泄露,下面的代码就是查看堆外内存的。可以写个定时任务,持续调用doReport方法来获取堆外内存。
init方法在项目初始化时调用一次,后续不要重复调用。
netty版本需要4.1以上
import io.netty.util.internal.PlatformDependent;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicLong;
/**
* @date 2020/10/19 11:14 上午
*/
public class DirectMemoryReporter {
private static final String BUSINESS_KEY = "netty_direct_memory";
private AtomicLong directMemory;
public void init(){
Field field = ReflectionUtils.findField(PlatformDependent.class,"DIRECT_MEMORY_COUNTER");
field.setAccessible(true);
try{
directMemory = ((AtomicLong)field.get(PlatformDependent.class));
}catch (Exception e){
}
}
public void doReport(String processName){
try{
long memoryInb = directMemory.get();
logger.error(processName + "**********" + BUSINESS_KEY + ":" + memoryInb);
}catch (Exception e){
}
}
}