Code Monkey home page Code Monkey logo

spring-cache-redis-scored's Introduction

About Spring Cache Redis Scored

Spring cache implementation using Redis sorted set, to prevent returning stale data in cache querying.

How to use

Add dependencies to your project

<dependency>
	<groupId>org.oxerr.spring.cache.redis.scored</groupId>
	<artifactId>spring-cache-redis-scored-spring-boot-starter</artifactId>
</dependency>

Mark your cached data class with supported annotation for ScoreResolver

import org.oxerr.spring.cache.redis.scored.score.resolver.annotated.annotation.Score;
// import javax.persistence.Version;
// import org.springframework.data.annotation.Version;

public class Book {

	/**
	 * Check org.oxerr.spring.cache.redis.scored.score.resolver.DefaultScoreResolver
	 * to see the supported annotations.
	 */
	@Score
	// @Version
	private long version;

}

Use Spring cache annotations to cache data

import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

@Cacheable(value = "books")
public Book getByIsbn(String isbn) {
	Book book = getByIsbnFromPersistence(isbn);

	// Maybe some slow works go here.

	return book;
}

/**
 * The @CachePut is required for preventing stale data.
 */
@CachePut(value = "books", key = "#result.getIsbn()")
public Book save(Book book) {

	// Make sure the book.version is incremental and incrementing thread-safely,
	// by using locking mechanism such as database record locking or optimistic locking.

	return saveToPersistence(isbn);
}

What is the different to implementation in spring-data-redis

The cache implementation RedisCache, in spring-data-redis uses set/setNX, get commands to set/get cache entries (see org.springframework.data.redis.cache.RedisCacheWriter), this may cause stale data returned from caching querying, in this scenario (see project spring-cache-redis-scored-example-spring-data-redis-cache).

Assuming we have 2 concurrent requests, request A querying data, and request B updating data, then the following scenario may happen:

  1. The cached data is expired.
  2. Request A queries data from persistence layer, got old data(version 1).
  3. Request B writes new data(version 2) into persistence layer.
  4. Request B evicts old data from cache.
  5. Request A puts old data(version 1) into cache.

Now we have the old data(version 1) in cache, and when querying from cache, the old data(version 1) will be returned, before the cache entry is expired or evicted.

But ScoredRedisCacheWriter uses zAdd, zRevRangeByScore and zRemRangeByScore, commands to set/get cache entries (see org.oxerr.spring.cache.redis.scored.ScoredRedisCacheWriter), this saves versioned data as sorted set in Redis with different scores, and always returns the newest versioned data, lets replay the above scenario, to demonstrate how spring-cache-redis-scored prevents stale data (see project spring-cache-redis-scored-example-spring-cache-redis-scored):

  1. The cached data is expired.
  2. Request A queries data from persistence layer, got old data(version 1).
  3. Request B writes new data(version 2) into persistence layer.
  4. Request B writes new data(version 2) into cache with score 2.
  5. Request A adds old data(version 1) into cache with score 1.

Now we have 2 versions of data in cache, the version 1 is score = 1, and the version 2 is score = 2. And when querying from cache, the newest version with maximum score(score = 2, version = 2) of data will be returned, by using Redis command ZREVRANGEBYSCORE key +inf -inf limit 0 1.

spring-cache-redis-scored's People

Contributors

sutra avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.