org.springframework.cache.CacheManager Java Examples

The following examples show how to use org.springframework.cache.CacheManager. 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
Source File: RedisCacheConfig.java    From spring-boot-vue-admin with 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 #2
Source File: LoadBalancerCacheAutoConfigurationTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: ResilientCartRepositoryImplTest.java    From yes-cart with 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 #4
Source File: CacheServiceImpl.java    From kfs with 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 #5
Source File: CacheUtilsTest.java    From api-layer with 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 #6
Source File: WebServiceDataSource.java    From conciliator with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: UserService.java    From scava with 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 #8
Source File: JCacheInterceptorTests.java    From spring4-understanding with Apache License 2.0 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.afterPropertiesSet();
	source.afterSingletonsInstantiated();
	return source;
}
 
Example #9
Source File: TwoLevelCacheTemplateTest.java    From n2o-framework with 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 #10
Source File: ResetCacheTestExecutionListener.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeTestMethod(TestContext testContext) {
    testContext.getApplicationContext().getBeansOfType(CacheManager.class).forEach(
            (cacheManagerName, cacheManager) ->
                    cacheManager.getCacheNames().forEach(name -> cacheManager.getCache(name).clear())
    );
}
 
Example #11
Source File: RedisConfig.java    From DouBiNovel with 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 #12
Source File: CompositeCacheManager.java    From lams with 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 #13
Source File: RedisConfig.java    From SpringCloud with 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 #14
Source File: EnableCachingIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: AbstractCacheAnnotationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: UserService.java    From 21-points with 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 #17
Source File: CompositeCacheManager.java    From spring-analysis-note with 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 #18
Source File: JCacheJavaConfigTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: ConfigurableCacheResolver.java    From haven-platform with 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 #20
Source File: RedisCacheConfig.java    From agile-service-old with 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 #21
Source File: JCacheInterceptorTests.java    From spring-analysis-note with 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 #22
Source File: CategoryImpexFederationFilterImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: CacheConfiguration.java    From redisson-spring-boot-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #24
Source File: RedisConfig.java    From light-reading-cloud with 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 #25
Source File: InitializrAutoConfiguration.java    From initializr with 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 #26
Source File: ReferenceApplication.java    From aws-refapp with 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 #27
Source File: CacheManagerEndpoint.java    From Moss with 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 #28
Source File: OrcidSmartNames.java    From conciliator with GNU General Public License v3.0 4 votes vote down vote up
@Autowired
public OrcidSmartNames(Config config, CacheManager cacheManager, ThreadPoolFactory threadPoolFactory, ConnectionFactory connectionFactory) {
    super(config, cacheManager, threadPoolFactory, connectionFactory);
}
 
Example #29
Source File: CachingConfigurerSupport.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public CacheManager cacheManager() {
	return null;
}
 
Example #30
Source File: CloudDatabaseConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public DataSource dataSource(CacheManager cacheManager) {
    log.info("Configuring JDBC datasource from a cloud provider");
    return connectionFactory().dataSource();
}