添加 Redis 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
开启缓存
@SpringBootApplication
@EnableCaching
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
添加缓存注解
@Override
@Cacheable(value = "UserCache", key = "'user.getAllUsers'")
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
Bean 实现序列化
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String address;
public User() {
}
public User(Integer id, String username, String address) {
this.id = id;
this.username = username;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username == null ? "" : username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address == null ? "" : address;
}
public void setAddress(String address) {
this.address = address;
}
}
指定 Redis 缓存地址
redis:
host: localhost
port: 6379
java @Override @CacheEvict(value = "UserCache", key = "‘user.getAllUsers‘") public void delete(Integer id) { System.out.println("删除了 id 为" + id + "的用户"); userMapper.delete(id); }
启动项目测试缓存
源码地址: github
原文:https://www.cnblogs.com/liyiran/p/11522841.html