I am trying to do Spring data CRUD Operation with Redis but mainly I need to store the auto increment key in Redis.
I have tried the simple CRUD operation for SpringData with Redis but there is no auto increment key feature.
How can I achieve this?
If you are using spring data redis repository, you can annotate the field with org.springframework.data.annotation.Id
for which value needs to be auto generated and a @RedisHash
annotation on its class.
@RedisHash("persons")
public class Person {
@Id String id;
String firstname;
String lastname;
Address address;
}
To now actually have a component responsible for storage and retrieval you need to define a repository interface.
public interface PersonRepository extends CrudRepository<Person, String> {
}
@Configuration
@EnableRedisRepositories
public class ApplicationConfig {
@Bean
public RedisConnectionFactory connectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
return template;
}
}
Given the setup above you can go on and inject PersonRepository into your components.
@Autowired PersonRepository repo;
public void basicCrudOperations() {
Person rand = new Person("rand", "al'thor");
rand.setAddress(new Address("emond's field", "andor"));
repo.save(rand); //1
repo.findOne(rand.getId()); //2
repo.count(); //3
repo.delete(rand); //4
}
- Generates a new id if current value is null or reuses an already set id value and stores properties of type Person inside the Redis Hash with key with pattern keyspace:id in this case eg. persons:5d67b7e1-8640-4475-beeb-c666fab4c0e5.
- Uses the provided id to retrieve the object stored at keyspace:id.
- Counts the total number of entities available within the keyspace persons defined by @RedisHash on Person.
- Removes the key for the given object from Redis.
Reference: http://docs.spring.io/spring-data/redis/docs/current/reference/html/