0

We have a requirement to Cache requests to a max of upto 2 categories per userId-sessionID pair. We are planning to use EhCache for this approach. The project is a spring boot application.

@Cacheable(value="products")
ProductList getProducts(String userID, String sessionID, String categoryID) {
   return getProductListForThisUserAndSessionAndCategory(userId, sessionId, categoryId;) 
}

The problem is how can I set the limit to a max of 2 cache elements per userID-sessionId when there could be more than one categories per user and session id pair?
One approach: Setting a partial key of sessionId and userID and create a custom cache which can accept a max two values per sessionID-userID key. How does EhCache support custom Caches?
Any other approaches?

MohanaRao SV
  • 1,117
  • 1
  • 8
  • 22
Shireesha
  • 11
  • 1
  • 3

1 Answers1

2

If I got your question right you will change the maximum number of mappings to cache you can config like this

import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;


@Configuration
@EnableCaching
public class CacheConfiguration {

    private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
    private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;


    @PreDestroy
    public void destroy() {
        log.info("Remove Cache Manager metrics");
        log.info("Closing Cache Manager");
    }

    public CacheConfiguration(JHipsterProperties jHipsterProperties) {

        jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
                CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
                        ResourcePoolsBuilder.heap(2))
                        .withExpiry(Expirations.timeToLiveExpiration(Duration.of(3600, TimeUnit.SECONDS)))
                        .build()
        );
    }

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        log.debug("Starting Ehcache");

        return cm -> {
            cm.createCache("products", jcacheConfiguration);
        };
    }

}
ali akbar azizkhani
  • 2,213
  • 5
  • 31
  • 48