Spring Boot 入门 Spring Boot 使用Redis缓存

本文详细介绍如何在SpringBoot项目中整合缓存功能,包括实体类、DAO、Service层的实现,以及使用SpringBoot的缓存注解进行数据读取、更新和删除的缓存管理。同时介绍了如何引入Redis作为缓存实现,并配置Redis的相关参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot 入门整合目录

SpringBoot 使用缓存

准备工作

实体类

student需要序列化 所以要实现Serializable

@Data
public class Student implements Serializable {

    private Integer id;
    private String name;
    private String gender;
}

DAO
@Mapper
public interface StudentDao {

    @Select("select id,name,gender from student where id = #{id}")
    Student findById(Integer id);

    @Update("update student set gender = #{gender} where id = {id}")
    void updateGenderById(Student student);

    @Delete("delete from student where id = #{id} ")
    void deleteById(Integer id);
}


service
public interface StudentService {

    Student getStudent(Integer id);

    Student updateStudent(Student student);

    void deleteById(Integer id);
}

serviceImpl

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Override
    public Student getStudent(Integer id) {
        return studentDao.findById(id);
    }

    @Override
    public Student updateStudent(Student student) {
        studentDao.updateGenderById(student);
        return studentDao.findById(student.id);
    }

    @Override
    public void deleteById(Integer id) {
        studentDao.deleteById(id);
    }
}

yml配置

yml中配置日志输出级别以观察SQL的执行情况

logging:
  level:
    com:
      cache:
        dao: debug
测试方法
  @Test
    public void test(){
        Student student = studentService.getStudent(1);
        System.out.println("名字是:"+student.getName()+"性别是:"+student.getGender());
        Student student1 = studentService.getStudent(1);
        System.out.println("名字是:"+student1.getName()+"性别是:"+student1.getGender());
    }

在这里插入图片描述

使用缓存

引入依赖

要开启Spring Boot的缓存功能,需要在pom中引入spring-boot-starter-cache:

 <!--缓存支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
启动同添加注解

Spring Boot入口类中加入@EnableCaching注解开启缓存功能:

@SpringBootApplication
//缓存支持
@EnableCaching
public class CacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}
service层添加注解

StudentService接口中加入缓存注解:

@CacheConfig(cacheNames = "student")
public interface StudentService {

    @Cacheable(key = "#p0")
    Student getStudent(Integer id);

    @CachePut(key = "#p0.id")
    Student updateStudent(Student student);

    @CacheEvict(key = "#p0", allEntries = true)
    void deleteById(Integer id);
}
缓存注解
  • @CacheConfig:主要用于配置该类中会用到的一些共用的缓存配置。在这里@CacheConfig(cacheNames = “student”):配置了该数据访问对象中返回的内容将存储于名为student的缓存对象中,我们也可以不使用该注解,直接通过@Cacheable自己配置缓存集的名字来定义;
  • @Cacheable:配置了方法的返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问。该注解主要有下面几个参数:
    – value、cacheNames:两个等同的参数(cacheNames为Spring 4新增,作为value的别名),用于指定缓存存储的集合名。由于Spring 4中新增了@CacheConfig,因此在Spring 3中原本必须有的value属性,也成为非必需项了;
    – key:缓存对象存储在Map集合中的key值,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpEL表达式,比如:@Cacheable(key = “#p0”):使用函数第一个参数作为缓存的key值;
    – condition:缓存对象的条件,非必需,也需使用SpEL表达式,只有满足表达式条件的内容才会被缓存,比如:@Cacheable(key = “#p0”, condition = “#p0.length() < 3”),表示只有当第一个参数的长度小于3的时候才会被缓存;
  • @CachePut:配置于函数上,能够根据参数定义条件来进行缓存,其缓存的是方法的返回值,它与@Cacheable不同的是,它每次都会真实调用函数,所以主要用于数据新增和修改操作上。它的参数与@Cacheable类似,具体功能可参考上面对@Cacheable参数的解析;
  • @CacheEvict:配置于函数上,通常用在删除方法上,用来从缓存中移除相应数据。除了同@Cacheable一样的参数之外,它还有下面两个参数:
    – allEntries:非必需,默认为false。当为true时,会移除所有数据;
    – beforeInvocation:非必需,默认为false,会在调用方法之后移除数据。当为true时,会在调用方法之前移除数据。
缓存实现

要使用上Spring Boot的缓存功能,还需要提供一个缓存的具体实现。本次使用的是Redis

Redis使用缓存

引入Redis依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
yml配置Redis
spring:
	redis:
	    host: localhost #Redis服务器地址
	    port: 6379 #Redis端口号
	    timeout: 300 # 连接超时时间(毫秒)
	    database: 1 # Redis数据库索引(默认为0)
	    password: # Redis 服务器密码,默认为空。生产中,一定要设置 Redis 密码!
	    jedis:
	      pool:
	        max-active: 300 # 连接池最大连接数,默认为 8 。使用负数表示没有限制。
	        max-idle: 8 # 默认连接数最大空闲的连接数,默认为 8 。使用负数表示没有限制。
	        min-idle: 0 # 默认连接池最小空闲的连接数,默认为 0 。允许设置 0 和 正数。
	        max-wait: -1 # 连接池最大阻塞等待时间,单位:毫秒。默认为 -1 ,表示不限制。
测试

测试只查询一遍
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值