How to invalidate Couchbase cache after update document

621 views Asked by At

I am using Couchbase as a cache for my spring boot application. but after updating my document i should wait for cache to expire in order to be refreshed. so basically deleting or updating any document dont invalidate it.

Here is my spring data repository :

public interface ConfigurationRepository extends CouchbaseRepository<Configuration, String> {

    @Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter}")
    @Cacheable(value = "Configuration_", unless = "#result == null")
    Optional<Configuration> getConfiguration();
}

my configuration :

spring.cache.cache-names=Configuration_
spring.cache.couchbase.expiration=10s

My document :

public class Configuration implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    private String id = UUID.randomUUID().toString();

    public List<ConfigElement> properties;

    @Version
    private long version;
}

my dependency :

    <dependency>
        <groupId>com.couchbase.client</groupId>
        <artifactId>couchbase-spring-cache</artifactId>
        <version>2.1.0</version>
    </dependency>

could you please suggest a way to invalidate cache after updating document in the bucket ?

1

There are 1 answers

0
gtiwari333 On BEST ANSWER

You need to use @CacheEvict to evict the previously cached items when they are changed or deleted.

@CacheEvict(cacheNames="books", allEntries=true) 
public void loadBooks(InputStream batch)

This process is useful for removing stale or unused data from the cache. As opposed to @Cacheable, @CacheEvict demarcates methods that perform cache eviction (that is, methods that act as triggers for removing data from the cache).

See https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/integration.html#cache-annotations-evict for more details