Java Code Examples for org.springframework.cache.CacheManager

The following examples show how to use org.springframework.cache.CacheManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
void loadBalancerCacheShouldNotOverrideExistingCaffeineCacheManager() {
	ApplicationContextRunner contextRunner = baseApplicationRunner()
			.withUserConfiguration(TestConfiguration.class);

	contextRunner.run(context -> {
		assertThat(context.getBeansOfType(CacheManager.class)).hasSize(2);
		assertThat(context.getBean("cacheManager"))
				.isInstanceOf(CaffeineCacheManager.class);
		assertThat(((CacheManager) context.getBean("cacheManager")).getCacheNames())
				.isEmpty();
		assertThat(
				((CacheManager) context.getBean("caffeineLoadBalancerCacheManager"))
						.getCacheNames()).hasSize(1);
		assertThat(
				((CacheManager) context.getBean("caffeineLoadBalancerCacheManager"))
						.getCacheNames())
								.contains("CachingServiceInstanceListSupplierCache");
	});

}
 
Example 2
Source Project: api-layer   Source File: CacheUtilsTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void givenValidCacheManager_whenGetAllRecords_thenReadAllStoredRecords() {
    CacheManager cacheManager = mock(CacheManager.class);
    Cache cache = mock(Cache.class);
    net.sf.ehcache.Cache ehCache = PowerMockito.mock(net.sf.ehcache.Cache.class);

    Map<Integer, String> entries = new HashMap<>();
    entries.put(1, "a");
    entries.put(2, "b");
    entries.put(3, "c");
    List<Object> keys = new ArrayList<>(entries.keySet());

    when(cacheManager.getCache("knownCacheName")).thenReturn(cache);
    when(cache.getNativeCache()).thenReturn(ehCache);
    when(ehCache.getKeys()).thenReturn(keys);
    when(ehCache.getAll(keys)).thenReturn(convert(entries));

    Collection<String> values = underTest.getAllRecords(cacheManager, "knownCacheName");
    assertNotNull(values);
    assertEquals(3, values.size());
    assertTrue(values.contains("a"));
    assertTrue(values.contains("b"));
    assertTrue(values.contains("c"));
}
 
Example 3
Source Project: kfs   Source File: CacheServiceImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void clearNamedCache(String cacheName) {

    try {
        CacheManager cm = CoreImplServiceLocator.getCacheManagerRegistry().getCacheManagerByCacheName(cacheName);
        if ( cm != null ) {
            Cache cache = cm.getCache(cacheName);
            if (cache != null) {
                cache.clear();
                if ( LOG.isDebugEnabled() ) {
                    LOG.debug( "Cleared " + cacheName + " cache." );
                }
            } else {
                // this is at debug level intentionally, since not all BOs have caches
                LOG.debug( "Unable to find cache for " + cacheName + ".");
            }
        } else {
            LOG.info( "Unable to find cache manager when attempting to clear " + cacheName );
        }
    } catch (RiceIllegalArgumentException e) {
        LOG.info( "Cache manager not found when attempting to clear " + cacheName );
    }

}
 
Example 4
Source Project: yes-cart   Source File: ResilientCartRepositoryImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetShoppingCartNullOrEmptyToken() throws Exception {

    final ShoppingCartStateService shoppingCartStateService = context.mock(ShoppingCartStateService.class, "shoppingCartStateService");
    final ShopService shopService = context.mock(ShopService.class, "shopService");
    final CartUpdateProcessor cartUpdateProcessor = context.mock(CartUpdateProcessor.class, "cartUpdateProcessor");
    final TaskExecutor taskExecutor = context.mock(TaskExecutor.class, "taskExecutor");
    final CacheManager cacheManager = context.mock(CacheManager.class, "cacheManager");
    final Cache cartCache = context.mock(Cache.class, "cartCache");

    context.checking(new Expectations() {{
        oneOf(cacheManager).getCache("web.shoppingCart"); will(returnValue(cartCache));
    }});

    final ResilientCartRepositoryImpl repo = new ResilientCartRepositoryImpl(shoppingCartStateService, shopService, cartUpdateProcessor, mockCartSerDes, 60, cacheManager, taskExecutor);

    assertNull(repo.getShoppingCart(null));
    assertNull(repo.getShoppingCart("  "));

    context.assertIsSatisfied();

}
 
Example 5
public WebServiceDataSource(
         Config config,
         CacheManager cacheManager,
         ThreadPoolFactory threadPoolFactory,
         ConnectionFactory connectionFactory) {
     super(config);
     this.cacheManager = cacheManager;
     this.threadPoolFactory = threadPoolFactory;
     this.connectionFactory = connectionFactory;

     this.threadPool = createThreadPool();

     Properties props = getConfig().getProperties();
     if(props.containsKey(Config.PROP_CACHE_ENABLED)) {
         setCacheEnabled(Boolean.valueOf(props.getProperty(Config.PROP_CACHE_ENABLED)));
     }
}
 
Example 6
Source Project: spring-boot-vue-admin   Source File: RedisCacheConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@Override
public CacheManager cacheManager() {
  // 初始化一个 RedisCacheWriter
  final RedisCacheWriter redisCacheWriter =
      RedisCacheWriter.nonLockingRedisCacheWriter(this.redisConnectionFactory);
  final RedisCacheConfiguration defaultCacheConfig =
      RedisCacheConfiguration.defaultCacheConfig()
          // 不缓存 null 值
          // .disableCachingNullValues()
          // 使用注解时的序列化、反序列化对
          .serializeKeysWith(MyRedisCacheManager.STRING_PAIR)
          .serializeValuesWith(MyRedisCacheManager.FASTJSON_PAIR);
  // 初始化RedisCacheManager
  return new MyRedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
 
Example 7
Source Project: DouBiNovel   Source File: RedisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    @Bean
    public CacheManager cacheManager() {

        // 设置序列化
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringSerializer))
                // value序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer))
//                .disableCachingNullValues()
                // 缓存过期时间
                .entryTtl(Duration.ofMinutes(5));

        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(lettuceConnectionFactory)
                .cacheDefaults(config)
                .transactionAware();
        @SuppressWarnings("serial")
        Set<String> cacheNames = new HashSet<String>() {
            {
                add("codeNameCache");
            }
        };
        builder.initialCacheNames(cacheNames);
        return builder.build();
    }
 
Example 8
Source Project: SpringCloud   Source File: RedisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        //对象的序列化
        RedisSerializationContext.SerializationPair valueSerializationPair
                = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer());
        //全局redis缓存过期时间
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))
//                .serializeKeysWith()
                .serializeValuesWith(valueSerializationPair);

        return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(factory), redisCacheConfiguration);
    }
 
Example 9
Source Project: 21-points   Source File: UserService.java    License: Apache License 2.0 5 votes vote down vote up
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserSearchRepository userSearchRepository, AuthorityRepository authorityRepository, CacheManager cacheManager) {
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
    this.userSearchRepository = userSearchRepository;
    this.authorityRepository = authorityRepository;
    this.cacheManager = cacheManager;
}
 
Example 10
protected JCacheOperationSource createOperationSource(CacheManager cacheManager,
		CacheResolver cacheResolver, CacheResolver exceptionCacheResolver, KeyGenerator keyGenerator) {

	DefaultJCacheOperationSource source = new DefaultJCacheOperationSource();
	source.setCacheManager(cacheManager);
	source.setCacheResolver(cacheResolver);
	source.setExceptionCacheResolver(exceptionCacheResolver);
	source.setKeyGenerator(keyGenerator);
	source.setBeanFactory(new StaticListableBeanFactory());
	source.afterPropertiesSet();
	source.afterSingletonsInstantiated();
	return source;
}
 
Example 11
Source Project: spring-analysis-note   Source File: CompositeCacheManager.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public Cache getCache(String name) {
	for (CacheManager cacheManager : this.cacheManagers) {
		Cache cache = cacheManager.getCache(name);
		if (cache != null) {
			return cache;
		}
	}
	return null;
}
 
Example 12
Source Project: agile-service-old   Source File: RedisCacheConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(24)); // 设置缓存有效期一小时
    return RedisCacheManager
            .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
            .cacheDefaults(redisCacheConfiguration).transactionAware().build();
}
 
Example 13
Source Project: light-reading-cloud   Source File: RedisConfig.java    License: MIT License 5 votes vote down vote up
/** 缓存管理器 */
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    //初始化一个RedisCacheWriter
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
    //设置CacheManager的值序列化方式为json序列化
    RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
    RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer);
    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
    //设置默认超过期时间是30秒
    defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(300));
    //初始化RedisCacheManager
    return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
 
Example 14
Source Project: haven-platform   Source File: ConfigurableCacheResolver.java    License: Apache License 2.0 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 15
public CategoryImpexFederationFilterImpl(final ShopFederationStrategy shopFederationStrategy,
                                         final List<String> roles,
                                         final ShopService shopService,
                                         final CategoryService categoryService,
                                         final CacheManager cacheManager,
                                         final List<String> cachesToFlushForTransientEntities) {
    super(shopFederationStrategy, roles, cacheManager, cachesToFlushForTransientEntities);
    this.shopService = shopService;
    this.categoryService = categoryService;
}
 
Example 16
Source Project: scava   Source File: UserService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository, CacheManager cacheManager, JwtAuthenticationConfig config) {
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
    this.authorityRepository = authorityRepository;
    this.cacheManager = cacheManager;
    this.config = config;
}
 
Example 17
Source Project: aws-refapp   Source File: ReferenceApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CacheManager createSimpleCacheManager() {
    SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
    List<Cache> caches = new ArrayList<>(2);
    caches.add(new ConcurrentMapCache("CacheCluster"));
    caches.add(new ConcurrentMapCache("GitHubSourceCode"));
    simpleCacheManager.setCaches(caches);

    return simpleCacheManager;
}
 
Example 18
Source Project: initializr   Source File: InitializrAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private Cache determineCache(Environment environment, CacheManager cacheManager) {
	if (cacheManager != null) {
		Binder binder = Binder.get(environment);
		boolean cache = binder.bind("spring.mustache.cache", Boolean.class).orElse(true);
		if (cache) {
			return cacheManager.getCache("initializr.templates");
		}
	}
	return new NoOpCache("templates");
}
 
Example 19
@Bean
CacheManager cacheManager() {
    Map<String, CacheConfig> config = new HashMap<>();
    // 创建一个名称为"testMap"的缓存,过期时间ttl为24分钟,同时最长空闲时maxIdleTime为12分钟。
    for (String s : value) {
        logger.info("初始化spring cache空间{}",s);
        config.put(s, new CacheConfig(ttl, maxIdleTime));
    }
    return new RedissonSpringCacheManager(redissonClient, config);
}
 
Example 20
Source Project: spring-analysis-note   Source File: JCacheInterceptorTests.java    License: MIT License 5 votes vote down vote up
protected JCacheOperationSource createOperationSource(CacheManager cacheManager,
		CacheResolver cacheResolver, CacheResolver exceptionCacheResolver, KeyGenerator keyGenerator) {

	DefaultJCacheOperationSource source = new DefaultJCacheOperationSource();
	source.setCacheManager(cacheManager);
	source.setCacheResolver(cacheResolver);
	source.setExceptionCacheResolver(exceptionCacheResolver);
	source.setKeyGenerator(keyGenerator);
	source.setBeanFactory(new StaticListableBeanFactory());
	source.afterSingletonsInstantiated();
	return source;
}
 
Example 21
@Bean
public CacheManager cacheManager() {
	SimpleCacheManager cm = new SimpleCacheManager();
	cm.setCaches(Arrays.asList(
			defaultCache(),
			new ConcurrentMapCache("primary"),
			new ConcurrentMapCache("secondary"),
			new ConcurrentMapCache("exception")));
	return cm;
}
 
Example 22
Source Project: Moss   Source File: CacheManagerEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/{cacheManager}")
public Object getAllCache(@PathVariable("cacheManager") String cacheManager){
    return applicationContext.getBeansOfType(CacheManager.class).entrySet().stream()
            .filter(en->en.getKey().equals(cacheManager))
            .map(en->en.getValue().getCacheNames())
            .findFirst().orElseGet(ArrayDeque::new);
}
 
Example 23
@Override
public void beforeTestMethod(TestContext testContext) {
    testContext.getApplicationContext().getBeansOfType(CacheManager.class).forEach(
            (cacheManagerName, cacheManager) ->
                    cacheManager.getCacheNames().forEach(name -> cacheManager.getCache(name).clear())
    );
}
 
Example 24
Source Project: n2o-framework   Source File: TwoLevelCacheTemplateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testWriteBehindPutEvictSync() throws InterruptedException {
    CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class);
    Cache cache = cacheManager.getCache("writeBehindCache");
    net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
    System.out.println("cache put:" + "test");
    nativeCache.putWithWriter(new Element(1, "test"));
    System.out.println("cache get:" + cache.get(1).get());
    System.out.println("cache evict:" + 1);
    nativeCache.removeWithWriter(1);
    System.out.println("sleep:" + 2 + "s");
    Thread.sleep(2000);
}
 
Example 25
@Test
public void testCustomCacheManager() {
	CacheManager customCm = ctx.getBean("customCacheManager", CacheManager.class);
	Object key = new Object();
	Object r1 = cs.customCacheManager(key);
	assertSame(r1, cs.customCacheManager(key));

	Cache cache = customCm.getCache("testCache");
	assertNotNull(cache.get(key));
}
 
Example 26
private void fooGetSimple(ApplicationContext context, FooService service) {
	CacheManager cacheManager = context.getBean(CacheManager.class);

	Cache cache = cacheManager.getCache("testCache");

	Object key = new Object();
	assertCacheMiss(key, cache);

	Object value = service.getSimple(key);
	assertCacheHit(key, value, cache);
}
 
Example 27
Source Project: lams   Source File: CompositeCacheManager.java    License: GNU General Public License v2.0 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 28
@Bean(name = "roleCacheManager")
public CacheManager roleCacheManager() {
    RedisCacheManager redisCacheManager = new RedisCacheManager(roleRedisTemplate);
    redisCacheManager.setDefaultExpiration(3600);
    return redisCacheManager;
}
 
Example 29
public SimpleExceptionCacheResolver(CacheManager cacheManager) {
	super(cacheManager);
}
 
Example 30
Source Project: yes-cart   Source File: ContentImageServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
public ContentImageServiceImpl(final CacheManager cacheManager) {
    super(cacheManager);
}