spring boot 2.1.4 緩存 Hazelcast實現(三)

Hazelcast官方提供了監控包,下載路徑https://hazelcast.org/download/java

裏面有Hazelcast英文文檔和相關包下載,下載Management Center包,是個war包,運行起來,登陸進去能夠看到監控,裏面有緩存命中和未命中的統計,可是發現緩存的數據沒有添加到監控中,這裏有3處緩存配置來源spring

一、若是是在hazelcast.xml文件中配置的,cache配置中啓用統計對應的配置項:<statistics-enabled>true</statistics-enabled>緩存

二、spring.cache.cache-names中配置的緩存配置項對應配置類ide

@Bean
	public static MutableConfiguration<Object, Object> defaultCacheConfiguration() {
		MutableConfiguration<Object, Object> defaultCacheConfiguration = new MutableConfiguration<>();
		defaultCacheConfiguration.setStatisticsEnabled(true);
		defaultCacheConfiguration.setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(new Duration(SECONDS, 10)));
		return defaultCacheConfiguration;
	}

這裏配置的緩存有效期是10秒,只是測試使用,能夠增大,默認hazelcast是永久有效測試

三、hibernate二級緩存的配置hibernate

查看JCacheRegionFactory源碼實現code

@SuppressWarnings("WeakerAccess")
	protected Cache<Object, Object> createCache(String regionName) {
		switch ( missingCacheStrategy ) {
			case CREATE_WARN:
				SecondLevelCacheLogger.INSTANCE.missingCacheCreated(
						regionName,
						ConfigSettings.MISSING_CACHE_STRATEGY, MissingCacheStrategy.CREATE.getExternalRepresentation()
				);
				return cacheManager.createCache( regionName, new MutableConfiguration<>() );
			case CREATE:
				return cacheManager.createCache( regionName, new MutableConfiguration<>() );
			case FAIL:
				throw new CacheException( "On-the-fly creation of JCache Cache objects is not supported [" + regionName + "]" );
			default:
				throw new IllegalStateException( "Unsupported missing cache strategy: " + missingCacheStrategy );
		}
	}

這裏在代碼中寫死了,使用的MutableConfiguration中的默認配置xml

這裏只能從新實現,實現類文檔

import java.util.Map;

import javax.cache.Cache;

import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.jcache.internal.JCacheRegionFactory;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BcJCacheRegionFactory extends JCacheRegionFactory {

	
	@SuppressWarnings("rawtypes")
	@Override
	protected void prepareForUse(SessionFactoryOptions settings, Map configValues) {
		super.prepareForUse(settings, configValues);
		log.info("hibernate 緩存 CacheManager:{}", getCacheManager());
	}

	@Override
	protected Cache<Object, Object> createCache(String regionName) {
		// super.createCache(regionName);
		log.info("建立緩存組:{}", regionName);
		return getCacheManager().createCache(regionName, CacheBeanConfigurerApapter.defaultCacheConfiguration());
	}

}

而後在配置文件中配置spring.jpa.properties.hibernate.cache.region.factory_class的值爲咱們新實現的這個類BcJCacheRegionFactory全路徑get

 

這樣就能夠在監控端看到全部的緩存統計數據了

相關文章
相關標籤/搜索