依赖
<!--SpringCache起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.7.3</version>
</dependency>
<!--Redis起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
常用注解
注解 | 作用 |
@EnableCaching | 开启缓存注解功能,加在启动类上 |
@Cacheable | 查询并返回缓存数据,没有则会生成缓存数据 |
@CachePut | 生成缓存数据 |
@CacheEvict | 删除缓存数据 |
yml配置文件
spring:
redis:
host: localhost
port: 6379
password: 123456
database: 2
Student
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
* 学生表
* </p>
*
* @author 翰戈.summer
* @since 2023-12-02
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_student")
public class Student implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 姓名
*/
private String name;
/**
* 性别;1代表男,2代表女
*/
private Integer gender;
/**
* 年龄
*/
private Integer age;
/**
* 乐观锁
*/
private Integer version;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
StudentController
import com.demo.pojo.entity.Student;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 学生表 前端控制器
* </p>
*
* @author 翰戈.summer
* @since 2023-12-02
*/
@RestController
@RequestMapping("/students")
public class StudentController {
@Cacheable(cacheNames = "studentCache", key = "#id")
@GetMapping("/{id}")
public Student getStudentById(@PathVariable Long id) {
//第一次测试,缓存数据。
String note = "第二次在这里打一个断点进行测试,发现没有进入断点,依然返回了数据。";
return new Student().setId(id);
}
}
查看结果
启动异常
如果出现以下异常,使用@SpringBootApplication注解的属性exclude = DataSourceAutoConfiguration.class,忽略数据源的配置。
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class