监视elipselink缓存L2,L1

时间:2015-04-22 05:59:01

标签: java jpa caching eclipselink

是否有工具或编程方法来监视eclipse链接的第一级,第二级缓存。我的目标是知道某个类缓存的实体数量。 这里有一些我找到的链接,但还不够:

http://www.eclipse.org/eclipselink/documentation/2.5/solutions/performance002.htm https://wiki.eclipse.org/EclipseLink/Examples/JPA/Monitoring

1 个答案:

答案 0 :(得分:2)

JPA没有指定这样的功能,但您可以使用EclipseLink内部功能来实现,例如:

L1(事务缓存,持久化上下文)

import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;
...
JpaEntityManager jem = em.unwrap(JpaEntityManager.class);
UnitOfWorkImpl ouw = jem.unwrap(UnitOfWorkImpl.class);
...
long count = countCachedEntitiesL1(clazz);

和相应的方法:

// Java 7
public long countCachedEntitiesL1(Class clazz) {
    long count = 0;
    for (Map.Entry<Object, Object> entity : ouw.getCloneMapping().entrySet()) {
        if (entity.getKey().getClass().equals(clazz)) {
            count++;
        }
    }
    return count;
}
// Java 8
public long countCachedEntitiesL1(Class clazz) {
    return ouw.getCloneMapping().keySet().stream()
        .filter(entity -> entity.getClass().equals(clazz))
        .count();
}


L2(共享缓存)

import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.sessions.server.ServerSession;
import org.eclipse.persistence.internal.sessions.IdentityMapAccessor;
...
JpaEntityManager jem = em.unwrap(JpaEntityManager.class);
ServerSession ss = jem.unwrap(ServerSession.class);
IdentityMapAccessor ima = (IdentityMapAccessor) ss.getIdentityMapAccessor();
...
int count = countCachedEntitiesL2(clazz);

和相应的方法:

public int countCachedEntitiesL2(Class clazz) {
    return ima.getIdentityMap(clazz).getSize();
}