Spring Boot与Redis的集成

  Redis是一个完全开源免费的、遵守BSD协议的、内存中的数据结构存储,它既可以作为数据库,也可以作为缓存和消息代理。因其性能优异等优势,目前已被很多企业所使用,但通常在企业中我们会将其作为缓存来使用。Spring Boot对Redis也提供了自动配置的支持,接下来本小节将讲解如何在Spring Boot项目中使用Redis。

添加Redis缓存

  添加Redis依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.4.4.RELEASE</version>
</dependency>

  添加@EnableCaching注解开启缓存:

@SpringBootApplication
@EnableCaching  //开启缓存
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

  添加@Cacheable注解来支持缓存:

@Cacheable(value="UserCache",key="'user.getAllUsers'")
@Override
public List<User> getAllUsers() {
    return userMapper.getAllUsers();
}

  使实体类实现可序列化接口:

public class User implements Serializable {

    private Integer id;
    private String username;
    private String address;
    ...

  指定Redis缓存主机地址:

spring.redis.host=127.0.0.1
spring.redis.port=6379

  启动项目,测试缓存使用:
  在没有使用Redis缓存之前,每刷新一次页面,都会执行一次查询数据库的操作,添加缓存后,会发现控制台中只出现了一次查询语句,这也就说明所配置的Redis缓存已经生效。

清除Redis缓存

  Redis中的缓存数据不会一直存在,当执行添加、更新和删除操作后,数据库中的数据会发生变化,而Redis缓存中的数据同样也需要进行相应的变化。为了保证Redis缓存中的数据与数据库中的一致,通常需要在执行添加、更新和删除操作之前清除缓存,然后在下一次执行查询操作时,将新的数据存储到Redis缓存中。

  @CacheEvict注解清除缓存:

@CacheEvict(value="UserCache",key="'user.getAllUsers'")
@Override
public void deleteUser(Integer id) {
    System.out.println("id:" + id);
    userMapper.delete(id);
}
原文地址:https://www.cnblogs.com/ooo0/p/11172329.html