下面列出了怎么用org.hibernate.stat.SecondLevelCacheStatistics的API类实例代码及写法,或者点击链接到github查看源代码。
@GET
@Path("/hibernate-cache/5")
@Produces("application/json")
public String step5_evictAndFindEntity() {
StringBuilder out = new StringBuilder();
// Evict entity from cache
ejb.evictEntity(1L);
// Reload evicted entity, should come from DB
// Stats should show a cache miss and a cache put
ejb.findEntity(1L, out);
SecondLevelCacheStatistics eventCacheStats = getCacheStatistics(EVENT_REGION_NAME);
printfAssert("Event entity cache miss: %d (expected %d)%n", eventCacheStats.getMissCount(), 1, out);
printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 1, out);
return out.toString();
}
@GET
@Path("/hibernate-cache/13")
@Produces("application/json")
public String step13_findExpiredEntity() throws Exception {
StringBuilder out = new StringBuilder();
// Wait long enough for entity to be expired from cache
Thread.sleep(1100);
// Find expiring entity, after expiration entity should come from DB
// Stats should show a cache miss and a cache put
ejb.findExpiringEntity(4L, out);
SecondLevelCacheStatistics personCacheStats = getCacheStatistics(PERSON_REGION_NAME);
printfAssert("Person entity cache miss: %d (expected %d)%n", personCacheStats.getMissCount(), 1, out);
printfAssert("Person entity cache put: %d (expected %d)%n", personCacheStats.getPutCount(), 1, out);
return out.toString();
}
/**
* @param sesFactory Session factory.
* @param idToChildCnt Number of children per entity.
* @param expHit Expected cache hits.
* @param expMiss Expected cache misses.
*/
@SuppressWarnings("unchecked")
private void assertCollectionCache(SessionFactory sesFactory, Map<Integer, Integer> idToChildCnt, int expHit,
int expMiss) {
sesFactory.getStatistics().clear();
Session ses = sesFactory.openSession();
try {
for (Map.Entry<Integer, Integer> e : idToChildCnt.entrySet()) {
Entity entity = (Entity)ses.load(Entity.class, e.getKey());
assertEquals((int)e.getValue(), entity.getChildren().size());
}
}
finally {
ses.close();
}
SecondLevelCacheStatistics stats =
sesFactory.getStatistics().getSecondLevelCacheStatistics(CHILD_COLLECTION_REGION);
assertEquals(expHit, stats.getHitCount());
assertEquals(expMiss, stats.getMissCount());
}
/**
* @param sesFactory Session factory.
* @param idToChildCnt Number of children per entity.
* @param expHit Expected cache hits.
* @param expMiss Expected cache misses.
*/
@SuppressWarnings("unchecked")
private void assertCollectionCache(SessionFactory sesFactory, Map<Integer, Integer> idToChildCnt, int expHit,
int expMiss) {
sesFactory.getStatistics().clear();
Session ses = sesFactory.openSession();
try {
for (Map.Entry<Integer, Integer> e : idToChildCnt.entrySet()) {
Entity entity = (Entity)ses.load(Entity.class, e.getKey());
assertEquals((int)e.getValue(), entity.getChildren().size());
}
}
finally {
ses.close();
}
SecondLevelCacheStatistics stats =
sesFactory.getStatistics().getSecondLevelCacheStatistics(CHILD_COLLECTION_REGION);
assertEquals(expHit, stats.getHitCount());
assertEquals(expMiss, stats.getMissCount());
}
/**
* Prints Hibernate L2 cache statistics to standard output.
*
* @param sesFactory Hibernate {@link SessionFactory}, for which to print
* statistics.
*/
private static void printStats(SessionFactory sesFactory) {
System.out.println("=== Hibernate L2 cache statistics ===");
for (String entityName : ENTITY_NAMES) {
System.out.println("\tEntity: " + entityName);
SecondLevelCacheStatistics stats =
sesFactory.getStatistics().getSecondLevelCacheStatistics(entityName);
System.out.println("\t\tPuts: " + stats.getPutCount());
System.out.println("\t\tHits: " + stats.getHitCount());
System.out.println("\t\tMisses: " + stats.getMissCount());
}
System.out.println("=====================================");
}
@GET
@Path("/hibernate-cache/1")
@Produces("application/json")
public String step1_persistEntities() {
// Persist 3 entities, stats should show 3 second level cache puts
ejb.persistEntities();
SecondLevelCacheStatistics eventCacheStats = getCacheStatistics(EVENT_REGION_NAME);
return printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 3);
}
@GET
@Path("/hibernate-cache/2")
@Produces("application/json")
public String step2_findEntity() {
StringBuilder out = new StringBuilder();
// Find one of the persisted entities, stats should show a cache hit
ejb.findEntity(1L, out);
SecondLevelCacheStatistics eventCacheStats = getCacheStatistics(EVENT_REGION_NAME);
printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1, out);
return out.toString();
}
@GET
@Path("/hibernate-cache/3")
@Produces("application/json")
public String step3_updateEntity() {
StringBuilder out = new StringBuilder();
// Update one of the persisted entities, stats should show a cache hit and a cache put
ejb.updateEntity(1L, out);
SecondLevelCacheStatistics eventCacheStats = getCacheStatistics(EVENT_REGION_NAME);
printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1, out);
printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 1, out);
return out.toString();
}
@GET
@Path("/hibernate-cache/6")
@Produces("application/json")
public String step6_deleteEntity() {
StringBuilder out = new StringBuilder();
// Remove cached entity, stats should show a cache hit
ejb.deleteEntity(1L, out);
SecondLevelCacheStatistics eventCacheStats = getCacheStatistics(EVENT_REGION_NAME);
printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1, out);
return out.toString();
}
@GET
@Path("/hibernate-cache/9")
@Produces("application/json")
public String step9_updateEntity() {
StringBuilder out = new StringBuilder();
// Update one of the persisted entities, stats should show a cache hit and a cache put
ejb.updateEntity(2L, out);
SecondLevelCacheStatistics eventCacheStats = getCacheStatistics(EVENT_REGION_NAME);
printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1, out);
printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 1, out);
return out.toString();
}
@GET
@Path("/hibernate-cache/11")
@Produces("application/json")
public String step11_persistExpiringEntity() {
StringBuilder out = new StringBuilder();
// Save cache-expiring entity, stats should show a second level cache put
ejb.persistExpiringEntity();
SecondLevelCacheStatistics personCacheStats = getCacheStatistics(PERSON_REGION_NAME);
printfAssert("Person entity cache puts: %d (expected %d)%n", personCacheStats.getPutCount(), 1, out);
return out.toString();
}
@GET
@Path("/hibernate-cache/12")
@Produces("application/json")
public String step12_findExpiringEntity() {
StringBuilder out = new StringBuilder();
// Find expiring entity, stats should show a second level cache hit
ejb.findExpiringEntity(4L, out);
SecondLevelCacheStatistics personCacheStats = getCacheStatistics(PERSON_REGION_NAME);
printfAssert("Person entity cache hits: %d (expected %d)%n", personCacheStats.getHitCount(), 1, out);
return out.toString();
}
public void testEmptySecondLevelCacheEntry() throws Exception {
getSessions().evictEntity( Item.class.getName() );
Statistics stats = getSessions().getStatistics();
stats.clear();
SecondLevelCacheStatistics statistics = stats.getSecondLevelCacheStatistics( Item.class.getName() );
Map cacheEntries = statistics.getEntries();
assertEquals( 0, cacheEntries.size() );
}
protected void printEntityCacheStats(String region, boolean printEntries) {
SecondLevelCacheStatistics stats = getCacheStats(region);
LOGGER.info(region + " Stats: \n\n\t" + stats + "\n");
if (printEntries) {
@SuppressWarnings("rawtypes")
Map cacheEntries = stats.getEntries();
LOGGER.info(Arrays.toString(cacheEntries.entrySet().toArray()));
}
}
protected SecondLevelCacheStatistics getCacheStats(String region) {
SecondLevelCacheStatistics stats = getSessionFactory().getStatistics().getSecondLevelCacheStatistics(region);
if (stats == null){
LOGGER.warn("No such cache: " + region);
}
return stats;
}
@Test
public void shouldCacheUserOnFind() {
User first = new User("first");
first.addNotificationFilter(new NotificationFilter("pipline", "stage1", StageEvent.Fails, true));
first.addNotificationFilter(new NotificationFilter("pipline", "stage2", StageEvent.Fails, true));
int originalUserCacheSize = sessionFactory.getStatistics().getSecondLevelCacheStatistics(User.class.getCanonicalName()).getEntries().size();
int originalNotificationsCacheSize = sessionFactory.getStatistics().getSecondLevelCacheStatistics(User.class.getCanonicalName() + ".notificationFilters").getEntries().size();
userDao.saveOrUpdate(first);
long userId = userDao.findUser("first").getId();
assertThat(sessionFactory.getStatistics().getSecondLevelCacheStatistics(User.class.getCanonicalName()).getEntries().size(), is(originalUserCacheSize + 1));
SecondLevelCacheStatistics notificationFilterCollectionCache = sessionFactory.getStatistics().getSecondLevelCacheStatistics(User.class.getCanonicalName() + ".notificationFilters");
assertThat(notificationFilterCollectionCache.getEntries().size(), is(originalNotificationsCacheSize + 1));
assertThat(notificationFilterCollectionCache.getEntries().get(userId), is(Matchers.notNullValue()));
}
private void setMemoryInfo(Model model) {
//系统的
MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
long usedSystemMemory = heapMemoryUsage.getUsed();
long maxSystemMemory = heapMemoryUsage.getMax();
model.addAttribute("usedSystemMemory", usedSystemMemory);
model.addAttribute("maxSystemMemory", maxSystemMemory);
//二级缓存的
Statistics statistics = (Statistics) model.asMap().get("statistics");
String[] secondLevelCacheRegionNames = statistics.getSecondLevelCacheRegionNames();
int totalMemorySize = 0;
int totalMemoryCount = 0;
int totalDiskCount = 0;
for(String secondLevelCacheRegionName : secondLevelCacheRegionNames) {
SecondLevelCacheStatistics secondLevelCacheStatistics =
statistics.getSecondLevelCacheStatistics(secondLevelCacheRegionName);
totalMemorySize += secondLevelCacheStatistics.getSizeInMemory();
totalMemoryCount += secondLevelCacheStatistics.getElementCountInMemory();
totalDiskCount += secondLevelCacheStatistics.getElementCountOnDisk();
}
model.addAttribute("totalMemorySize", totalMemorySize);
model.addAttribute("totalMemoryCount", totalMemoryCount);
model.addAttribute("totalDiskCount", totalDiskCount);
}
private static SecondLevelCacheStatistics getCacheStatistics(String regionName) {
return emf.unwrap(SessionFactory.class).getStatistics()
.getSecondLevelCacheStatistics(regionName);
}
private SecondLevelCacheStatistics getCacheStatistics(String regionName) {
return em.unwrap(Session.class).getSessionFactory().getStatistics()
.getSecondLevelCacheStatistics(regionName);
}
private SecondLevelCacheStatistics getCacheStatistics(String regionName) {
return emf.unwrap(SessionFactory.class).getStatistics()
.getSecondLevelCacheStatistics(regionName);
}
/**
* @see StatisticsServiceMBean#getSecondLevelCacheStatistics(java.lang.String)
*/
public SecondLevelCacheStatistics getSecondLevelCacheStatistics(String regionName) {
return stats.getSecondLevelCacheStatistics(regionName);
}
protected void printQueryCacheStats(String region) {
SecondLevelCacheStatistics stats = getCacheStats(region);
LOGGER.info(region + " Stats: \n\n\t" + stats + "\n");
}
public SecondLevelCacheStatistics getSecondLevelCacheStatistics(
String regionName) {
return null;
}