Ole S
Ole S

Reputation: 76

How to I set a time to live (TTL) for a specific line record within a hash key in a Redis database using Spring Boot and RedisTemplate

I have an EmployeeDaoImpl class that has a saveEmployee method which uses the putIfAbsent method of hashOperations to store the JSON string in Redis.


@Service
public class EmployeeDaoImpl implements IEmployeeDao {

    private static final String MAPPING_KEY = "EMPLOYEES_REG_TEMP_RECORDS";
    
    private final ObjectMapper objectMapper;
    private final StringRedisTemplate stringRedisTemplate;
    @Resource(name = "stringRedisTemplate")  // 'stringRedisTemplate' is defined as a Bean in AppConfig.java
    private HashOperations<String, String, String> hashOperations;
    
    public EmployeeDaoImpl(ObjectMapper objectMapper, StringRedisTemplate stringRedisTemplate) {
        this.objectMapper = objectMapper;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    
    @Override
    public void saveEmployee(Employee emp) throws JsonProcessingException {
        String json = objectMapper.writeValueAsString(emp);
        hashOperations.putIfAbsent(MAPPING_KEY, emp.getRequestRefId(), json);
    }

}

This screenshot is how the employee record is saved in Redis enter image description here

I am able to expire the key this way


stringRedisTemplate.expire(key, 30, TimeUnit.SECONDS)

But now I want to be able to set TTL for every single line record in the EMPLOYEES_REG_TEMP_RECORDS hash key without expiring the key

Upvotes: 0

Views: 1517

Answers (1)

Guy Royse
Guy Royse

Reputation: 4312

Fields within a Hash in Redis cannot be expired. Redis only supports expiration on keys, not values within a key.

Upvotes: 1

Related Questions