使用EnableCaching的Spring启动应用程序如何检索番石榴缓存内容

时间:2016-10-07 10:21:02

标签: spring hibernate guava spring-test spring-cache

它使用启用了缓存的Spring启动应用程序。

环境(pom.xml):

弹簧:

org.springframework.boot:spring-boot-starter-amqp:jar:1.3.3.RELEASE
org.springframework:spring-messaging:jar:4.2.5.RELEASE
org.springframework.amqp:spring-rabbit:jar:1.5.4.RELEASE
org.springframework.retry:spring-retry:jar:1.1.2.RELEASE
org.springframework:spring-core:jar:4.2.5.RELEASE:compile
org.springframework.cloud:spring-cloud-aws-context:jar:1.0.4.RELEASE
org.springframework:spring-context:jar:4.2.5.RELEASE
org.springframework.data:spring-data-jpa:jar:1.9.4.RELEASE
org.springframework:spring-context-support:jar:4.2.5.RELEASE

休眠

org.hibernate:hibernate-validator:jar:5.2.2.Final
org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final
com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:jar:2.6.5
org.hibernate:hibernate-entitymanager:jar:5.1.0.Final
org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final
org.hibernate:hibernate-java8:jar:5.1.0.Final
org.hibernate:hibernate-envers:jar:5.1.0.Final

配置缓存(在Spring启动应用程序上):

@Configuration
@EnableCaching
public class ApplicationCacheConfig extends CachingConfigurerSupport {

    /**
     * Configuration Table Cache
     */
    public static final String CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME = "CONFIGURATION_TABLE_FIND_BY_ID_CACHE";

    public static final String CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE_NAME = "CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE";

    @Bean
    @Override
    public CacheManager cacheManager() {

        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        Collection<Cache> caches = Lists.newArrayList();

        caches.addAll(buildConfigurationCache());

        simpleCacheManager.setCaches(caches);
        return simpleCacheManager;
    }

    private Collection<Cache> buildConfigurationCache() {

        List<Cache> caches = Lists.newArrayList();

        // This cache never expires and don't have a maximum size because the table Configuration is not transactional
        GuavaCache cacheFindById = new GuavaCache(CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME,
                CacheBuilder.newBuilder().build());
        caches.add(cacheFindById);

        // This cache never expires and don't have a maximum size because the table Configuration is not transactional
        GuavaCache cacheFindByService = new GuavaCache(CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE_NAME,
                CacheBuilder.newBuilder().build());
        caches.add(cacheFindByService);

        return caches;
    }
}

Hibernate实体:

@Entity
@Table(name = Configuration.TABLE_NAME)
@DynamicUpdate
public class Configuration implements Serializable {

    public static final String TABLE_NAME = "configuration";

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "id")
    @Convert(converter = ConfigurationConverter.class)
    private ConfigurationEnum id;

    @Column(name = "service", nullable = false)
    @NotNull
    @Convert(converter = ServiceConverter.class)
    private ServiceEnum service;

}

存储库(Spring-data):

public interface ConfigurationRepository extends PagingAndSortingRepository<Configuration, Integer>,
        JpaSpecificationExecutor<Configuration> {

    @Cacheable(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME)
    Configuration findById(ConfigurationEnum configurationEnum);

    @Cacheable(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE_NAME)
    List<Configuration> findByService(ServiceEnum service);

}

配置枚举:

@Getter
@AllArgsConstructor
public enum ConfigurationEnum {

    CONFIG_1(1),
    CONFIG_2(2);

    private int id;
}

配置转换器:

@Converter
public class ConfigurationConverter implements AttributeConverter<ConfigurationEnum, Integer> {

    @Override
    public Integer convertToDatabaseColumn(ConfigurationEnum key) {
        return key == null ? null : (int) key.getId();
    }

    @Override
    public ConfigurationEnum convertToEntityAttribute(Integer key) {

        return key == null ? null : Stream.of(ConfigurationEnum.values())
                     .filter(step -> key.equals(step.getId()))
                     .findFirst()
                     .orElse(null);
    }
}

测试IT:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationIT.class)
@WebAppConfiguration
@Transactional
public class ConfigurationCacheIT {

    @Autowired
    ConfigurationRepository configurationRepository;

    @Autowired
    protected CacheManager cacheManager;

    @Test
    public void configuration_findById_cache_success() {

        Configuration config = configurationRepository.findById(ConfigurationEnum.CONFIG_1);
        // An ORM request is performed - CHECK
        Assert.assertNotNull(step); // TEST OK
        Cache.ValueWrapper entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1.getId());
        Assert.assertNull(entry); OK

        config = configurationRepository.findById(ConfigurationEnum.CONFIG_1);
        // No ORM request is performed - CHECK
        Assert.assertNotNull(step); // TEST OK

        entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1.getId());
        Assert.assertNotNull(entry); **// TEST FAIL !!!**

        entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1.name());
        Assert.assertNotNull(entry); **// TEST FAIL !!!**

        entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1);
        Assert.assertNotNull(entry); **// TEST FAIL !!!**
    }

    protected Cache.ValueWrapper getCacheEntry(String cacheName, Object key) {
        return cacheManager.getCache(cacheName).get(key);
    }

    @Test
    public void configuration_findByAll_without_cache_success() {

    ArrayList<Configuration> list1 = Lists.newArrayList(configurationRepository.findAll());
    // An ORM request is executed
    Assert.assertNotNull(list1);
    Assert.assertEquals(ConfigurationEnum.values().length, list1.size());

    ArrayList<Configuration> list2 = Lists.newArrayList(configurationRepository.findAll());
    // Another ORM request is executed
    Assert.assertNotNull(list2);
    Assert.assertEquals(ConfigurationEnum.values().length, list2.size());
    }

}

我的问题是为什么我的测试失败了?

1 个答案:

答案 0 :(得分:0)

实际上这不是问题。

我正在使用休闲架构:

  • App-mdw (中间件层)(带@EnableCaching注释的Spring启动应用程序)
  • App-ws (Web服务层)(没有@EnableCaching注释的Spring启动应用程序)

以上测试是在应用程序 App-ws 上执行的,并且注释不会继承,这就是缓存无效的原因。

正确的断言是:

entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1);
        Assert.assertNotNull(entry)