1.创建springboot项目
引入依赖
2.编写实体类
public class User implements Serializable {
private Integer id;
private String username;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
'}';
}
}
3.配置application
spring.redis.host=127.0.0.1
spring.redis.database=0
spring.redis.port=6379
spring.redis.password=123456
#springcache
spring.cache.cache-names=c1
4.编写service
注意:
在启动类上加上这个注解
@EnableCaching
@Service
@CacheConfig(cacheNames = "c1")
public class UserService {
//查询
@Cacheable
public User getUserById(Integer id){
System.out.println("getUserById>>>"+id);
User user = new User();
user.setId(id);
return user;
}
//删除
@CacheEvict
public void delUserById(Integer id){
System.out.println("delUserById>>>"+id);
}
//修改
@CachePut(key = "#user.id")
public User upUserById(User user){
return user;
}
}
5.编写测试类,进行测试
@SpringBootTest
class SpringCacheApplicationTests {
@Autowired
private UserService userService;
@Test
void contextLoads() {
User u1=userService.getUserById(1);
User u2=userService.getUserById(2);
System.out.println(u1);
System.out.println(u2);
}
}