簡體   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