Java Code Examples for org.springframework.cache.CacheManager

The following are top voted examples for showing how to use org.springframework.cache.CacheManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: vics   File: CacheConfig.java   Source Code and License 8 votes vote down vote up
@Primary
@Bean(name = "stats")
public CacheManager stats(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    cacheManager.setUsePrefix(true);
    cacheManager.setDefaultExpiration(TWENTY_MINS_SECS);
    return cacheManager;
}
 
Example 2
Project: BCDS   File: CacheConfiguration.java   Source Code and License 7 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

        String name = entity.getName();
        if (name == null || entity.getJavaType() != null) {
            name = entity.getJavaType().getName();
        }
        Assert.notNull(name, "entity cannot exist without a identifier");

        net.sf.ehcache.Cache cache = cacheManager.getCache(name);
        if (cache != null) {
            cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
            net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
            cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
        }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
}
 
Example 3
Project: buenojo   File: CacheConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public CacheManager cacheManager(JHipsterProperties jHipsterProperties) {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap());
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

        String name = entity.getName();
        if (name == null || entity.getJavaType() != null) {
            name = entity.getJavaType().getName();
        }
        Assert.notNull(name, "entity cannot exist without a identifier");

        net.sf.ehcache.Cache cache = cacheManager.getCache(name);
        if (cache != null) {
            cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds());
            net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
            cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
        }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
}
 
Example 4
Project: JavaQuarkBBS   File: RedisConfig.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    //设置缓存过期时间
    //rcm.setDefaultExpiration(60);//秒
    return rcm;
}
 
Example 5
Project: spring-boot-start-current   File: SpringCacheConfig.java   Source Code and License 6 votes vote down vote up
@Bean
public CacheManager cacheManager ( RedisTemplate redisTemplate ) {
	RedisCacheManager redisCacheManager = new RedisCacheManager( redisTemplate );
	// 默认30分钟
	redisCacheManager.setDefaultExpiration( defaultExpiration );
	redisCacheManager.setExpires( expires );
	redisCacheManager.setUsePrefix( usePrefix );
	return redisCacheManager;
}
 
Example 6
Project: gameofcode   File: CacheConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public CacheManager cacheManager(JHipsterProperties jHipsterProperties) {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap());
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

        String name = entity.getName();
        if (name == null || entity.getJavaType() != null) {
            name = entity.getJavaType().getName();
        }
        Assert.notNull(name, "entity cannot exist without a identifier");

        net.sf.ehcache.Cache cache = cacheManager.getCache(name);
        if (cache != null) {
            cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds());
            net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
            cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
        }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
}
 
Example 7
Project: spring4-understanding   File: GuavaCacheManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testDynamicMode() {
	CacheManager cm = new GuavaCacheManager();
	Cache cache1 = cm.getCache("c1");
	assertTrue(cache1 instanceof GuavaCache);
	Cache cache1again = cm.getCache("c1");
	assertSame(cache1again, cache1);
	Cache cache2 = cm.getCache("c2");
	assertTrue(cache2 instanceof GuavaCache);
	Cache cache2again = cm.getCache("c2");
	assertSame(cache2again, cache2);
	Cache cache3 = cm.getCache("c3");
	assertTrue(cache3 instanceof GuavaCache);
	Cache cache3again = cm.getCache("c3");
	assertSame(cache3again, cache3);

	cache1.put("key1", "value1");
	assertEquals("value1", cache1.get("key1").get());
	cache1.put("key2", 2);
	assertEquals(2, cache1.get("key2").get());
	cache1.put("key3", null);
	assertNull(cache1.get("key3").get());
	cache1.evict("key3");
	assertNull(cache1.get("key3"));
}
 
Example 8
Project: conciliator   File: Application.java   Source Code and License 6 votes vote down vote up
@Bean
public CacheManager cacheManager(@Autowired Config config) {
    long ttl = Long.valueOf(config.getProperties().getProperty(Config.PROP_CACHE_TTL));

    double pctOfHeap = Double.valueOf(config.getProperties().getProperty(Config.PROP_CACHE_SIZE));
    long cacheSizeMB = new Double(Runtime.getRuntime().maxMemory() * pctOfHeap / 1048576.0).longValue();

    LogFactory.getLog(getClass()).info(
            String.format("Initializing cache TTL=%d secs, size=%d MB (%.2f percent of max heap)",
                    ttl, cacheSizeMB, pctOfHeap * 100));

    org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Object.class, Object.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                            .heap(cacheSizeMB, MemoryUnit.MB))
            .withExpiry(Expirations.timeToLiveExpiration(new org.ehcache.expiry.Duration(ttl, TimeUnit.SECONDS)))
            .build();

    Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
    caches.put(CACHE_DEFAULT, cacheConfiguration);

    EhcacheCachingProvider provider = (EhcacheCachingProvider) javax.cache.Caching.getCachingProvider();

    // when our cacheManager bean is re-created several times for
    // diff test configurations, this provider seems to hang on to state
    // causing cache settings to not be right. so we always close().
    provider.close();

    DefaultConfiguration configuration = new DefaultConfiguration(
            caches, provider.getDefaultClassLoader());

    return new JCacheCacheManager(
            provider.getCacheManager(provider.getDefaultURI(), configuration));
}
 
Example 9
Project: jhipster-ribbon-hystrix   File: _CacheConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean<% if (hibernateCache == 'ehcache') { %>
public CacheManager cacheManager(JHipsterProperties jHipsterProperties) {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap());
    log.debug("Registering Ehcache Metrics gauges");<% if (databaseType == 'sql') { %>
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

        String name = entity.getName();
        if (name == null || entity.getJavaType() != null) {
            name = entity.getJavaType().getName();
        }
        Assert.notNull(name, "entity cannot exist without a identifier");

        net.sf.ehcache.Cache cache = cacheManager.getCache(name);
        if (cache != null) {
            cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds());
            net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
            cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
        }
    }<% } %>
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;<% }
 
Example 10
Project: the-mathmos-server   File: W3CSearchServiceImpTest.java   Source Code and License 6 votes vote down vote up
@Before
   public void setUp() throws Exception {
annotationUtils = new AnnotationUtils();
searchQueryUtils = new SearchQueryUtils();
template = mock(ElasticsearchTemplate.class);
client = mock(Client.class);
when(template.getClient()).thenReturn(client);
textSearchService = mock(TextSearchService.class);
mixedCache = mock(Cache.class);
cacheManager = mock(CacheManager.class);
when(cacheManager.getCache(anyString())).thenReturn(mixedCache);
when(mixedCache.get(queryString)).thenReturn(null);
Map map = new HashMap();
mixedCache.put(queryStringWithPage, map);
//when(mixedCache.get(queryStringWithPage)).thenReturn(new ValueWrapper())
impl = new W3CSearchServiceImpl(annotationUtils, template, textSearchService, cacheManager);
   }
 
Example 11
Project: JRediClients   File: RedissonCacheStatisticsProvider.java   Source Code and License 5 votes vote down vote up
@Override
public CacheStatistics getCacheStatistics(final CacheManager cacheManager, final RedissonCache cache) {
    final DefaultCacheStatistics defaultCacheStatistics = new DefaultCacheStatistics();
    defaultCacheStatistics.setSize((long) cache.getNativeCache().size());
    defaultCacheStatistics.setGetCacheCounts(cache.getCacheHits(), cache.getCacheMisses());
    return defaultCacheStatistics;
}
 
Example 12
Project: JavaQuarkBBS   File: RedisConfig.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    //设置缓存过期时间
    //rcm.setDefaultExpiration(60);//秒
    return rcm;
}
 
Example 13
Project: iBase4J-Common   File: JedisConfig.java   Source Code and License 5 votes vote down vote up
@Bean
@Qualifier("redisTemplate")
public CacheManager redisCacheManager(RedisTemplate<Serializable, Serializable> redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    cacheManager.setTransactionAware(true);
    cacheManager.setDefaultExpiration(PropertiesUtil.getInt("redis.expiration", 10));
    return cacheManager;
}
 
Example 14
Project: SpringBootLogExecutionTime   File: CacheableCustomerServiceImpl.java   Source Code and License 5 votes vote down vote up
public CacheableCustomerServiceImpl(CustomerRepository customerRepository,
                                    CacheManager cacheManager,
                                    CustomerKeyGenerator customerKeyGenerator) {

    super(customerRepository);
    this.cacheManager = cacheManager;
    this.customerKeyGenerator = customerKeyGenerator;
}
 
Example 15
Project: dhus-core   File: TestCacheUserService.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void setUp ()
{
   this.userService = ApplicationContextProvider.getBean (
         fr.gael.dhus.service.UserService.class);
   this.cacheManager =
         ApplicationContextProvider.getBean (CacheManager.class);
   authenticate ();
}
 
Example 16
Project: dhus-core   File: TestCacheSymDS.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void setUp ()
{
   this.extPoint = ApplicationContextProvider.getBean (SolrReplicationExtensionPoint.class);
   this.extPoint.setSearchService(new SearchServiceForTest());

   this.cacheManager = ApplicationContextProvider.getBean (CacheManager.class);
   this.userService = ApplicationContextProvider.getBean (UserService.class);
   this.userDao = ApplicationContextProvider.getBean (UserDao.class);
   this.productService = ApplicationContextProvider.getBean (ProductService.class);
   this.productDao = ApplicationContextProvider.getBean (ProductDao.class);
   authenticate ();

   productService.count ();
}
 
Example 17
Project: sentry   File: CacheConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    log.debug("Creating Guava cache manager");
    CacheBuilder<Object, Object> thirtyMinuteBuilder = CacheBuilder.newBuilder().expireAfterAccess(30, TimeUnit.MINUTES).recordStats();
    CacheBuilder<Object, Object> oneHourBuilder = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.HOURS).recordStats();
    CacheBuilder<Object, Object> threeHoursBuilder = CacheBuilder.newBuilder().expireAfterAccess(3, TimeUnit.HOURS).recordStats();

    Map<String, CacheBuilder<Object, Object>> builderMap = new LinkedHashMap<>();
    builderMap.put("schedule", oneHourBuilder);
    builderMap.put("team", threeHoursBuilder);
    builderMap.put("roster", threeHoursBuilder);
    builderMap.put("results", thirtyMinuteBuilder);
    builderMap.put("legacyPlayer", threeHoursBuilder);
    builderMap.put("player", threeHoursBuilder);
    builderMap.put("banList", threeHoursBuilder);
    builderMap.put("transactions", thirtyMinuteBuilder);
    builderMap.put("overwatch", threeHoursBuilder);

    GuavaCacheManager guavaCacheManager = new GuavaCacheManager() {
        @Override
        protected com.google.common.cache.Cache<Object, Object> createNativeGuavaCache(String name) {
            CacheBuilder<Object, Object> builder = builderMap.get(name);
            if (builder != null) {
                log.debug("Creating cache for {}: {}", name, builder.toString());
                return builder.build();
            }
            log.debug("Creating fallback cache for {}", name);
            return super.createNativeGuavaCache(name);
        }
    };
    guavaCacheManager.setCacheBuilder(thirtyMinuteBuilder);
    return guavaCacheManager;
}
 
Example 18
Project: leafer   File: ArticleServiceImpl.java   Source Code and License 5 votes vote down vote up
@Autowired
public ArticleServiceImpl(ArticleMapper articleMapper, CacheManager cacheManager) {
    this.articleMapper = articleMapper;
    this.cacheManager = cacheManager;
    this.idWorker = new IdWorker(1);
    this.logger = LoggerFactory.getLogger(ArticleServiceImpl.class);
}
 
Example 19
Project: nixmash-blog   File: PostServiceImpl.java   Source Code and License 5 votes vote down vote up
@Autowired
public PostServiceImpl(PostRepository postRepository, TagRepository tagRepository, LikeRepository likeRepository, PostImageRepository postImageRepository, PostMetaRepository postMetaRepository, CategoryRepository categoryRepository, ApplicationSettings applicationSettings, CacheManager cacheManager) {
    this.postRepository = postRepository;
    this.tagRepository = tagRepository;
    this.likeRepository = likeRepository;
    this.postImageRepository = postImageRepository;
    this.postMetaRepository = postMetaRepository;
    this.categoryRepository = categoryRepository;
    this.applicationSettings = applicationSettings;
    this.cacheManager = cacheManager;
}
 
Example 20
Project: MI-S   File: RedisConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate){
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    //设置缓存过期时间
    //rcm.setDefaultExpiration(60);//秒
    return rcm;
}
 
Example 21
Project: lams   File: CompositeCacheManager.java   Source Code and License 5 votes vote down vote up
@Override
public Cache getCache(String name) {
	for (CacheManager cacheManager : this.cacheManagers) {
		Cache cache = cacheManager.getCache(name);
		if (cache != null) {
			return cache;
		}
	}
	return null;
}
 
Example 22
Project: lams   File: CompositeCacheManager.java   Source Code and License 5 votes vote down vote up
@Override
public Collection<String> getCacheNames() {
	Set<String> names = new LinkedHashSet<String>();
	for (CacheManager manager : this.cacheManagers) {
		names.addAll(manager.getCacheNames());
	}
	return Collections.unmodifiableSet(names);
}
 
Example 23
Project: microservices-sample-project   File: AppConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    return CacheConfig.createCacheManager(
    		"UserDaoImpl"
    		, "RoleDaoImpl"
    		, "PermissionDaoImpl");
}
 
Example 24
Project: pokemon   File: AppConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    return CacheConfig.createCacheManager(
    		"UserDaoImpl"
    		, "RoleDaoImpl"
    		, "PermissionDaoImpl");
}
 
Example 25
Project: DanmuChat   File: RedisConfig.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate){
    RedisCacheManager redisCacheManager =new RedisCacheManager(redisTemplate);
    //设置缓存过期时间
    redisCacheManager.setDefaultExpiration(60);//秒
    return redisCacheManager;
}
 
Example 26
Project: qualitoast   File: UserService.java   Source Code and License 5 votes vote down vote up
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserSearchRepository userSearchRepository, PersistentTokenRepository persistentTokenRepository, AuthorityRepository authorityRepository, CacheManager cacheManager) {
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
    this.userSearchRepository = userSearchRepository;
    this.persistentTokenRepository = persistentTokenRepository;
    this.authorityRepository = authorityRepository;
    this.cacheManager = cacheManager;
}
 
Example 27
Project: CityPower-Build-Sample   File: CacheConfig.java   Source Code and License 5 votes vote down vote up
@Bean
    public CacheManager cacheManager() {
    	RedisTemplate ops = redisTemplate(redisConnectionFactory());
//    	RedisSerializer ser = ops.getValueSerializer();
        RedisCacheManager manager = new RedisCacheManager(ops);
        manager.setDefaultExpiration(300);
 
        return manager;
    }
 
Example 28
Project: lemon-dubbo-message   File: RedisConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@SuppressWarnings("rawtypes")
public CacheManager cacheManager(RedisTemplate redisTemplate) {
	RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
	redisCacheManager.setDefaultExpiration(60*5); //设置一个默认的过期时间/秒
	return redisCacheManager;
}
 
Example 29
Project: AntiSocial-Platform   File: CachingConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod="shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
    CacheConfiguration cacheConfiguration = new CacheConfiguration();
    cacheConfiguration.setName("categoryCache");
    cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");
    cacheConfiguration.setMaxEntriesLocalHeap(1000);


    net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
    //config.addCache(cacheConfiguration);
    config.defaultCache(cacheConfiguration);

    return net.sf.ehcache.CacheManager.newInstance(config);
}
 
Example 30
Project: data-migration   File: RedisConfiguration.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    //设置缓存过期时间
    rcm.setDefaultExpiration(60);//秒
    return rcm;
}
 
Example 31
Project: memcached-spring-boot   File: MemcachedAutoConfigurationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void whenUsingCustomCacheManagerThenMemcachedCustomCacheManagerLoaded() {
    loadContext(CacheWithCustomCacheManagerConfiguration.class);

    CacheManager cacheManager = this.applicationContext.getBean(CacheManager.class);

    assertThat(cacheManager).isInstanceOf(ConcurrentMapCacheManager.class);
}
 
Example 32
Project: haven-platform   File: ConfigurableCacheResolver.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @param cacheManagers
 * @param defaultCacheManager optional default cache manager, usually it in memory local cache
 */
public ConfigurableCacheResolver(Map<String, CacheManager> cacheManagers,
                                 CacheManager defaultCacheManager,
                                 List<CacheInvalidator> cacheInvalidators) {
    this.cacheManagers = cacheManagers;
    this.defaultCacheManager = defaultCacheManager;
    this.cacheInvalidators = cacheInvalidators;
}
 
Example 33
Project: Qihua   File: CacheAspectSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Return the {@link CacheOperationMetadata} for the specified operation.
 * <p>
 * Resolve the {@link CacheResolver} and the {@link KeyGenerator} to be used for the operation.
 * 
 * @param operation the operation
 * @param method the method on which the operation is invoked
 * @param targetClass the target type
 * @return the resolved metadata for the operation
 */
protected CacheOperationMetadata getCacheOperationMetadata(CacheOperation operation, Method method,
    Class<?> targetClass) {

  CacheOperationCacheKey cacheKey = new CacheOperationCacheKey(operation, method, targetClass);
  CacheOperationMetadata metadata = metadataCache.get(cacheKey);
  if (metadata == null) {
    KeyGenerator operationKeyGenerator;
    if (StringUtils.hasText(operation.getKeyGenerator())) {
      operationKeyGenerator = getBean(operation.getKeyGenerator(), KeyGenerator.class);
    } else {
      operationKeyGenerator = getKeyGenerator();
    }
    CacheResolver operationCacheResolver;
    if (StringUtils.hasText(operation.getCacheResolver())) {
      operationCacheResolver = getBean(operation.getCacheResolver(), CacheResolver.class);
    } else if (StringUtils.hasText(operation.getCacheManager())) {
      CacheManager cacheManager = getBean(operation.getCacheManager(), CacheManager.class);
      operationCacheResolver = new SimpleCacheResolver(cacheManager);
    } else {
      operationCacheResolver = getCacheResolver();
    }
    metadata =
        new CacheOperationMetadata(operation, method, targetClass, operationKeyGenerator, operationCacheResolver);
    metadataCache.put(cacheKey, metadata);
  }
  return metadata;
}
 
Example 34
Project: spring-boot-concourse   File: CacheManagerCustomizers.java   Source Code and License 5 votes vote down vote up
/**
 * Customize the specified {@link CacheManager}. Locates all
 * {@link CacheManagerCustomizer} beans able to handle the specified instance and
 * invoke {@link CacheManagerCustomizer#customize(CacheManager)} on them.
 * @param <T> the type of cache manager
 * @param cacheManager the cache manager to customize
 * @return the cache manager
 */
public <T extends CacheManager> T customize(T cacheManager) {
	List<CacheManagerCustomizer<CacheManager>> customizers = findCustomizers(
			cacheManager);
	AnnotationAwareOrderComparator.sort(customizers);
	for (CacheManagerCustomizer<CacheManager> customizer : customizers) {
		customizer.customize(cacheManager);
	}
	return cacheManager;
}
 
Example 35
Project: spring-boot-concourse   File: CacheAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
JCacheManagerCustomizer myCustomizer() {
	return new JCacheManagerCustomizer() {
		@Override
		public void customize(javax.cache.CacheManager cacheManager) {
			MutableConfiguration<?, ?> config = new MutableConfiguration<Object, Object>();
			config.setExpiryPolicyFactory(
					CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES));
			config.setStatisticsEnabled(true);
			cacheManager.createCache("custom1", config);
			cacheManager.destroyCache("bar");
		}
	};
}
 
Example 36
Project: spring4-understanding   File: CacheAspectSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Return the {@link CacheOperationMetadata} for the specified operation.
 * <p>Resolve the {@link CacheResolver} and the {@link KeyGenerator} to be
 * used for the operation.
 * @param operation the operation
 * @param method the method on which the operation is invoked
 * @param targetClass the target type
 * @return the resolved metadata for the operation
 */
protected CacheOperationMetadata getCacheOperationMetadata(
		CacheOperation operation, Method method, Class<?> targetClass) {

	CacheOperationCacheKey cacheKey = new CacheOperationCacheKey(operation, method, targetClass);
	CacheOperationMetadata metadata = this.metadataCache.get(cacheKey);
	if (metadata == null) {
		KeyGenerator operationKeyGenerator;
		if (StringUtils.hasText(operation.getKeyGenerator())) {
			operationKeyGenerator = getBean(operation.getKeyGenerator(), KeyGenerator.class);
		}
		else {
			operationKeyGenerator = getKeyGenerator();
		}
		CacheResolver operationCacheResolver;
		if (StringUtils.hasText(operation.getCacheResolver())) {
			operationCacheResolver = getBean(operation.getCacheResolver(), CacheResolver.class);
		}
		else if (StringUtils.hasText(operation.getCacheManager())) {
			CacheManager cacheManager = getBean(operation.getCacheManager(), CacheManager.class);
			operationCacheResolver = new SimpleCacheResolver(cacheManager);
		}
		else {
			operationCacheResolver = getCacheResolver();
		}
		metadata = new CacheOperationMetadata(operation, method, targetClass,
				operationKeyGenerator, operationCacheResolver);
		this.metadataCache.put(cacheKey, metadata);
	}
	return metadata;
}
 
Example 37
Project: spring4-understanding   File: CompositeCacheManager.java   Source Code and License 5 votes vote down vote up
@Override
public Cache getCache(String name) {
	for (CacheManager cacheManager : this.cacheManagers) {
		Cache cache = cacheManager.getCache(name);
		if (cache != null) {
			return cache;
		}
	}
	return null;
}
 
Example 38
Project: spring-boot-concourse   File: CacheManagerCustomizers.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<CacheManagerCustomizer<CacheManager>> findCustomizers(
		CacheManager cacheManager) {
	if (this.applicationContext == null) {
		return Collections.emptyList();
	}
	Class<?> cacheManagerClass = cacheManager.getClass();
	List<CacheManagerCustomizer<CacheManager>> customizers = new ArrayList<CacheManagerCustomizer<CacheManager>>();
	for (CacheManagerCustomizer customizer : getBeans(CacheManagerCustomizer.class)) {
		if (canCustomize(customizer, cacheManagerClass)) {
			customizers.add(customizer);
		}
	}
	return customizers;
}
 
Example 39
Project: spring4-understanding   File: CacheResolverCustomizationTests.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
	ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
	this.cacheManager = context.getBean("cacheManager", CacheManager.class);
	this.anotherCacheManager = context.getBean("anotherCacheManager", CacheManager.class);

	this.simpleService = context.getBean(SimpleService.class);
}
 
Example 40
Project: spring   File: CacheAspectSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Return the {@link CacheOperationMetadata} for the specified operation.
 * <p>Resolve the {@link CacheResolver} and the {@link KeyGenerator} to be
 * used for the operation.
 * @param operation the operation
 * @param method the method on which the operation is invoked
 * @param targetClass the target type
 * @return the resolved metadata for the operation
 */
protected CacheOperationMetadata getCacheOperationMetadata(
		CacheOperation operation, Method method, Class<?> targetClass) {

	CacheOperationCacheKey cacheKey = new CacheOperationCacheKey(operation, method, targetClass);
	CacheOperationMetadata metadata = this.metadataCache.get(cacheKey);
	if (metadata == null) {
		KeyGenerator operationKeyGenerator;
		if (StringUtils.hasText(operation.getKeyGenerator())) {
			operationKeyGenerator = getBean(operation.getKeyGenerator(), KeyGenerator.class);
		}
		else {
			operationKeyGenerator = getKeyGenerator();
		}
		CacheResolver operationCacheResolver;
		if (StringUtils.hasText(operation.getCacheResolver())) {
			operationCacheResolver = getBean(operation.getCacheResolver(), CacheResolver.class);
		}
		else if (StringUtils.hasText(operation.getCacheManager())) {
			CacheManager cacheManager = getBean(operation.getCacheManager(), CacheManager.class);
			operationCacheResolver = new SimpleCacheResolver(cacheManager);
		}
		else {
			operationCacheResolver = getCacheResolver();
		}
		metadata = new CacheOperationMetadata(operation, method, targetClass,
				operationKeyGenerator, operationCacheResolver);
		this.metadataCache.put(cacheKey, metadata);
	}
	return metadata;
}
 
Example 41
Project: xlator   File: RedisCacheStatisticsProvider.java   Source Code and License 5 votes vote down vote up
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager, RedisCache cache) {
    DefaultCacheStatistics statistics = new DefaultCacheStatistics();
    // @see http://redis.io/commands/INFO
    RedisConnection connection = RedisConnectionUtils.getConnection(this.redisConnectionFactory);
    try {
        Properties props = connection.info();
        Long hitCount = Long.parseLong(props.getProperty("keyspace_hits"));
        Long missCount = Long.parseLong(props.getProperty("keyspace_misses"));
        statistics.setGetCacheCounts(hitCount, missCount);
    } finally {
        RedisConnectionUtils.releaseConnection(connection, this.redisConnectionFactory);
    }
    return statistics;
}
 
Example 42
Project: spring4-understanding   File: EnableCachingTests.java   Source Code and License 5 votes vote down vote up
@Test
public void emptyConfigSupport() {
	ConfigurableApplicationContext context =
			new AnnotationConfigApplicationContext(EmptyConfigSupportConfig.class);

	CacheInterceptor ci = context.getBean(CacheInterceptor.class);
	assertNotNull(ci.getCacheResolver());
	assertEquals(SimpleCacheResolver.class, ci.getCacheResolver().getClass());
	assertSame(context.getBean(CacheManager.class),
			((SimpleCacheResolver)ci.getCacheResolver()).getCacheManager());
	context.close();
}
 
Example 43
Project: spring-boot-concourse   File: CacheStatisticsAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
public javax.cache.CacheManager jCacheCacheManager() {
	javax.cache.CacheManager cacheManager = Caching
			.getCachingProvider(HazelcastCachingProvider.class.getName())
			.getCacheManager();
	MutableConfiguration<Object, Object> config = new MutableConfiguration<Object, Object>();
	config.setStatisticsEnabled(true);
	cacheManager.createCache("books", config);
	cacheManager.createCache("speakers", config);
	return cacheManager;
}
 
Example 44
Project: caching-demo   File: CacheConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
    simpleCacheManager.setCaches(Arrays.asList(
            buildPostCodeCache(),
            buildTemperatureCache(),
            buildSharesCache()
    ));
    return simpleCacheManager;
}
 
Example 45
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CacheStatisticsAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
public javax.cache.CacheManager jCacheCacheManager() {
	javax.cache.CacheManager cacheManager = Caching
			.getCachingProvider(HazelcastCachingProvider.class.getName())
			.getCacheManager();
	MutableConfiguration<Object, Object> config = new MutableConfiguration<Object, Object>();
	config.setStatisticsEnabled(true);
	cacheManager.createCache("books", config);
	cacheManager.createCache("speakers", config);
	return cacheManager;
}
 
Example 46
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CacheAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
public net.sf.ehcache.CacheManager customEhCacheCacheManager() {
	net.sf.ehcache.CacheManager cacheManager = mock(
			net.sf.ehcache.CacheManager.class);
	given(cacheManager.getStatus()).willReturn(Status.STATUS_ALIVE);
	given(cacheManager.getCacheNames()).willReturn(new String[0]);
	return cacheManager;
}
 
Example 47
Project: spring   File: CompositeCacheManager.java   Source Code and License 5 votes vote down vote up
@Override
public Cache getCache(String name) {
	for (CacheManager cacheManager : this.cacheManagers) {
		Cache cache = cacheManager.getCache(name);
		if (cache != null) {
			return cache;
		}
	}
	return null;
}
 
Example 48
Project: spring-boot-concourse   File: CachePublicMetrics.java   Source Code and License 5 votes vote down vote up
private MultiValueMap<String, CacheManagerBean> getCacheManagerBeans() {
	MultiValueMap<String, CacheManagerBean> cacheManagerNamesByCacheName = new LinkedMultiValueMap<String, CacheManagerBean>();
	for (Map.Entry<String, CacheManager> entry : this.cacheManagers.entrySet()) {
		for (String cacheName : entry.getValue().getCacheNames()) {
			cacheManagerNamesByCacheName.add(cacheName,
					new CacheManagerBean(entry.getKey(), entry.getValue()));
		}
	}
	return cacheManagerNamesByCacheName;
}
 
Example 49
Project: spring-playground   File: CacheConfig.java   Source Code and License 5 votes vote down vote up
@Bean
    public CacheManager redisCacheManager(RedisTemplate redisTemplate) {
//        redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

        return cacheManager;
    }
 
Example 50
Project: java-platform   File: CacheConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@Override
public CacheManager cacheManager() {
	try {
		return springEmbeddedCacheManagerFactoryBean().getObject();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 51
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: HazelcastCacheStatisticsProvider.java   Source Code and License 5 votes vote down vote up
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager,
		HazelcastCache cache) {
	DefaultCacheStatistics statistics = new DefaultCacheStatistics();
	LocalMapStats mapStatistics = ((IMap<?, ?>) cache.getNativeCache())
			.getLocalMapStats();
	statistics.setSize(mapStatistics.getOwnedEntryCount());
	statistics.setGetCacheCounts(mapStatistics.getHits(),
			mapStatistics.getGetOperationCount() - mapStatistics.getHits());
	return statistics;
}
 
Example 52
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CacheManagerCustomizersTests.java   Source Code and License 5 votes vote down vote up
@Test
public void customizeNoConfigurableApplicationContext() {
	CacheManagerCustomizers invoker = new CacheManagerCustomizers();
	ApplicationContext context = mock(ApplicationContext.class);
	invoker.setApplicationContext(context);
	invoker.customize(mock(CacheManager.class));
	verifyZeroInteractions(context);
}
 
Example 53
Project: my-spring-cache-redis   File: CompositeCacheManager.java   Source Code and License 5 votes vote down vote up
@Override
public Cache getCache(String name) {
	for (CacheManager cacheManager : this.cacheManagers) {
		Cache cache = cacheManager.getCache(name);
		if (cache != null) {
			return cache;
		}
	}
	return null;
}
 
Example 54
Project: the-mathmos-server   File: W3CAnnotationSearchServiceImplTest.java   Source Code and License 5 votes vote down vote up
@Before
   public void setUp() throws Exception {

annotationUtils = new AnnotationUtils();
searchQueryUtils = new SearchQueryUtils();
template = mock(ElasticsearchTemplate.class);
client = mock(Client.class);
when(template.getClient()).thenReturn(client);
textSearchService = mock(TextSearchService.class);
cacheManager = mock(CacheManager.class);
impl = new W3CAnnotationSearchServiceImpl(annotationUtils, template, textSearchService, cacheManager);
   }
 
Example 55
Project: spring-boot-concourse   File: CacheAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
public net.sf.ehcache.CacheManager customEhCacheCacheManager() {
	net.sf.ehcache.CacheManager cacheManager = mock(
			net.sf.ehcache.CacheManager.class);
	given(cacheManager.getStatus()).willReturn(Status.STATUS_ALIVE);
	given(cacheManager.getCacheNames()).willReturn(new String[0]);
	return cacheManager;
}
 
Example 56
Project: conciliator   File: VIAF.java   Source Code and License 5 votes vote down vote up
@Autowired
public VIAF(Config config, CacheManager cacheManager, ThreadPoolFactory threadPoolFactory, ConnectionFactory connectionFactory) {
    super(config, cacheManager, threadPoolFactory, connectionFactory);

    setCacheEnabled(true);

    spf = SAXParserFactory.newInstance();
}
 
Example 57
Project: conciliator   File: OpenLibrary.java   Source Code and License 5 votes vote down vote up
@Autowired
public OpenLibrary(Config config, CacheManager cacheManager, ThreadPoolFactory threadPoolFactory, ConnectionFactory connectionFactory) {
    super(config, cacheManager, threadPoolFactory, connectionFactory);

    // openlibrary seems to enforce non-simultaneous queries
    getThreadPool().setPoolSize(1);
}
 
Example 58
Project: mojito   File: CachingConfig.java   Source Code and License 5 votes vote down vote up
@Bean
@Override
public CacheManager cacheManager() {
    Cache defaultCache = new ConcurrentMapCache("default");
    Cache localesCache = new ConcurrentMapCache("locales");

    SimpleCacheManager manager = new SimpleCacheManager();
    manager.setCaches(Arrays.asList(defaultCache, localesCache));

    return manager;
}
 
Example 59
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CacheManagerCustomizers.java   Source Code and License 5 votes vote down vote up
/**
 * Customize the specified {@link CacheManager}. Locates all
 * {@link CacheManagerCustomizer} beans able to handle the specified instance and
 * invoke {@link CacheManagerCustomizer#customize(CacheManager)} on them.
 * @param <T> the type of cache manager
 * @param cacheManager the cache manager to customize
 * @return the cache manager
 */
public <T extends CacheManager> T customize(T cacheManager) {
	List<CacheManagerCustomizer<CacheManager>> customizers = findCustomizers(
			cacheManager);
	AnnotationAwareOrderComparator.sort(customizers);
	for (CacheManagerCustomizer<CacheManager> customizer : customizers) {
		customizer.customize(cacheManager);
	}
	return cacheManager;
}
 
Example 60
Project: spring-boot-concourse   File: AbstractJmxCacheStatisticsProvider.java   Source Code and License 5 votes vote down vote up
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager, C cache) {
	try {
		ObjectName objectName = internalGetObjectName(cache);
		return (objectName == null ? null : getCacheStatistics(objectName));
	}
	catch (MalformedObjectNameException ex) {
		throw new IllegalStateException(ex);
	}
}