Configuration
@Configuration public class RedisConfiguration { @Bean public LettuceConnectionFactory redisConnectionFactory() { ConfigFile configFile = new ConfigFile(); RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(configFile.getRedisHost()); configuration.setPassword(configFile.getRedisPassword()); return new LettuceConnectionFactory(configuration); } @Bean public StringRedisTemplate redisTemplate() { return new StringRedisTemplate(redisConnectionFactory()); } }
You can use RedisTemplate
instead of StringRedisTemplate
.
Redis Repository
@RedisHash("Student") public class Student implements Serializable { public enum Gender { MALE, FEMALE } @Id private String id; private String name; private Gender gender; private int grade; // ... }
The Spring Data Repository
@Repository public interface StudentRepository extends CrudRepository<Student, String> {}
Data Access Using StudentRepository
Saving a New Student Object
Student student = new Student( "Eng2015001", "John Doe", Student.Gender.MALE, 1); studentRepository.save(student);
Retrieving an Existing Student Object
Student retrievedStudent = studentRepository.findById("Eng2015001").get();
Updating an Existing Student Object
retrievedStudent.setName("Richard Watson"); studentRepository.save(student);
Deleting Existing Student Data
studentRepository.deleteById(student.getId());
Find All Student Data
Student engStudent = new Student( "Eng2015001", "John Doe", Student.Gender.MALE, 1); Student medStudent = new Student( "Med2015001", "Gareth Houston", Student.Gender.MALE, 2); studentRepository.save(engStudent); studentRepository.save(medStudent);
References
https://docs.spring.io/spring-data/redis/docs/current/reference/html/
https://www.baeldung.com/spring-data-redis-tutorial