1. 程式人生 > >spring boot 2.1.4 快取 Hazelcast實現(三)

spring boot 2.1.4 快取 Hazelcast實現(三)

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

裡面有Hazelcast英文文件和相關包下載,下載Management Center包,是個war包,執行起來,登入進去可以看到監控,裡面有快取命中和未命中的統計,但是發現快取的資料沒有新增到監控中,這裡有3處快取配置來源

1、如果是在hazelcast.xml檔案中配置的,cache配置中啟用統計對應的配置項:<statistics-enabled>true</statistics-enabled>

2、spring.cache.cache-names中配置的快取配置項對應配置類

@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是永久有效

3、hibernate二級快取的配置

檢視JCacheRegionFactory原始碼實現

@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中的預設配置

這裡只能重新實現,實現類

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.jps.properties.hibernate.cache.region.factory_class的值為我們新實現的這個類BcJCacheRegionFactory全路徑

 

這樣就可以在監控端看到所有的