Starting to integrate Redis
in a Spring Boot
application that needs concurrent access to it (Redis
), I need advice on the best practice in order to continue the implementation.
Redis
access is setup like this:
@Configurationpublic class RedisConfig { @Bean public LettuceConnectionFactory redisConnectionFactory() { try { return new LettuceConnectionFactory(); } catch (Exception e) { // log... } } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); try { redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(redisConnectionFactory); } catch (Exception e) { // log ... } return redisTemplate; }}
There are entities saved in Redis
using a repository like this:
@Getter@Setter@ToString@RedisHash@NoArgsConstructorpublic class Item { @Id private String id; // ...}
@Repositorypublic interface ItemRepository extends CrudRepository<Item, String> {}
A service to manage the items:
@Service@RequiredArgsConstructorpublic class ItemsService { private final ItemRepository itemRepository;... private manageItem(Item item) { // ... // set item data // NEEDS LOCKING itemRepository.save(item); // ... }...}
At this point, must implement the concurrent access to this Redis data. Reading multiple articles about this, I wonder what is the right implementation to follow in order to be able to delete an item
from Redis when this is not accessed by another save call from the ItemRepository
, in a scheduled task. It's a cleanup when the item
was not used for a specific time and meets some conditions. So the task should come, make a list of them and delete them if they are not accessed at the time (even unlikely), by trying to acquire a lock and delete. If the lock is not successful, should let them alone for the next run.
So the question is: in the @Repository
context, should implement a RedisLockRegistry
or a custom lock by using some Redis commands? How would this look like? What is the right beans design?