Skip to content

Latest commit

 

History

History
187 lines (146 loc) · 3.45 KB

File metadata and controls

187 lines (146 loc) · 3.45 KB
theme background class highlighter lineNumbers info drawings transition title mdc
seriph
text-center
shikiji
false
## Cacheable Redis Spring Presentation
persist
slide-left
Cacheable Redis Spring Presentation
true

Cacheable Redis Spring Presentation


What are we going to learn today?

  • @Cacheable - annotation provided by Spring
  • Redis - how is works

Cache annotations

  • @Cacheable
  • @CacheEvict
  • @CachePut

@Cacheable

Define a cache for the list of users

@Cacheable(value = "users-cache")
public List<User> getAllUsers() {
  return userRepository.findAll();
}

@CacheEvict - single entry

Evict cache

@CacheEvict(value = "users-cache", key = "#id")
public User deleteUser(String id) {
  return userRepository.deleteById(id);
}

@CacheEvict - all entries

Evict cache

@CacheEvict(value="users-cache",allEntries = true)
public List<User> updateUsers(List<User> users) {
  return userRepository.saveAll(users);
}

@CachePut

Update cache

@CachePut(value = "users-cache", key = "#user.id")
public User updateUser(User user) {
    return userRepository.save(user);
}

Redis

  • distributed cache
  • key value store

Get started with Redis

  • redis docker container
  • redis-cli command

Redis docker container

version: '3.7'
services:
  redis:
    image: redis:latest
    hostname: redis
    container_name: redis
    restart: always
    command: sh -c "redis-server --save 20 1 --requirepass dev"
    ports:
      - "6379:6379"

And you run docker compose up -d


redis-cli

redis-cli -h localhost
# authenticate
localhost:6379> AUTH dev
OK
# get all keys
localhost:6379> KEYS *
 1) "users-cache::1"
# get value for cache key
localhost:6379> GET "users-cache::1"

Best practices and gotchas

  • Invocation of cacheable methods from the same class
  • evict vs put
  • reusing the same cache, but with different response
  • use cache keys usage whenever possible