Spring-data-redis实战CRUD

1. 环境 & 配置

redis服务端使用redis-5.0.0

核心依赖

<dependency>
    <groupId>org.springframework.datagroupId>
    <artifactId>spring-data-redisartifactId>
    <version>2.0.3.RELEASEversion>
dependency>

<dependency>
    <groupId>redis.clientsgroupId>
    <artifactId>jedisartifactId>
    <version>2.9.0version>
    <type>jartype>
dependency>

配置注入redis相关bean, @EnableRedisRepositories必须注解,指向下面的dao层。

@Configuration
@EnableRedisRepositories(basePackages = "xyz.cglzwz.dao")
public class RedisConfig {
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConFactory
                = new JedisConnectionFactory();
        return jedisConFactory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }
}

JedisConnectionFactory类的一些属性已经弃用了,如host、port。这里采用默认本地主机6379端口。
@EnableRedisRepositories(basePackages = “xyz.cglzwz.dao”) 注解是必须的。因为下面的dao接口是直接继承Spring-data-redis的一个通用接口。

2. 核心实现

实体类使用@RedisHash(“Student”)注解,并实现序列化借口。实现redis对对象存储操作的基础。

@RedisHash("Student")
public class Student implements Serializable {
    public enum Gender {
        MALE, FEMALE
    }

    private String id;
    private String name;
    private Gender gender;
    private Integer grade;

    /** getter and setter **/
}

dao层如上所说,直接一个继承org.springframework.data.repository.CrudRepository的接口

@Repository
public interface StudentRepository extends CrudRepository<Student, String> { }

下面就是些简单的CRUD业务实现

@Service
public class StudentServiceImpl implements StudentService {
    private final static Logger log = LoggerFactory.getLogger(StudentServiceImpl.class);

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void create(Student student) {
        studentRepository.save(student);
    }

    @Override
    public Student retrieve(String id) {
        return studentRepository.findById(id).get();
    }

    @Override
    public void update(Student student) {
        Student retrieveStudent = studentRepository.findById(student.getId()).get();
        if (student.getName() != null) {
            retrieveStudent.setName(student.getName());
        }
        if (student.getGrade() != null) {
            retrieveStudent.setGrade(student.getGrade());
        }
        studentRepository.save(retrieveStudent);
    }

    @Override
    public void delete(String id) {
        studentRepository.deleteById(id);
    }

    @Override
    public List<Student> findAll() {
        List<Student> students = new ArrayList<Student>();
        studentRepository.findAll().forEach(students::add);
        return students;
    }
}

=> 完整代码地址

效果预览

Spring-data-redis实战CRUD_第1张图片
Spring-data-redis实战CRUD_第2张图片

你可能感兴趣的:(SSM,框架开发,Redis)