繁体   English   中英

具有EnableCaching的Spring Boot应用程序如何检索番石榴缓存内容

[英]Spring boot application with EnableCaching How to retrieve guava cache content

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

环境(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 Boot应用程序上):

@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;
    }
}

休眠实体:

@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数据):

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());
    }

}

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

实际上,这不是一个问题。

我正在使用休闲架构:

  • App-mdw (中间件层)(带有@EnableCaching批注的Spring boot App)
  • App-ws (WebServices层)(不带@EnableCaching批注的Spring Boot App)

上面的测试是在应用程序App-ws上执行的,并且注释没有继承,这就是缓存无法正常工作的原因。

正确的断言是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM