SpringBoot缓存注解使用(无数据库操作)
缓存注解介绍
-
@EnableCaching注解:开启注解缓存的支持
-
@Cacheable注解:对方法的查询结果进行缓存
-
@CachePut注解:更新缓存
-
@CacheEvict注解:删除缓存
-
@Caching注解:处理复杂缓存
-
@CacheConfig注解:统筹管理@CachePut、@CacheEvict、@Caching
项目层次结构
![](https://img-blog.csdnimg.cn/13e41815d7d74837a1810be374ab6953.png)
pom文件,创建项目时勾上web\thymeleaf\lombok,没有的再
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
pojo层
User
package com.my.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String comment;
}
dao层
UserDao
package com.my.dao;
import com.my.pojo.User;
import java.util.List;
public interface UserDao {
public List<User> findAll();
public int deleteUser(int id);
public int addUser(User user);
public int updateUser(User user);
public User findById(int id);
}
UserDaoImpl
package com.my.dao;
import com.my.pojo.User;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements UserDao{
//public static List<User> users; 使用add()会报错
public static List<User> users=new ArrayList<>();
static {
User user1=new User();
user1.setId(1);
user1.setName("李琳琳");
user1.setComment("我是一个永远你也打不死的人!");
users.add(user1);
User user2=new User();
user2.setId(2);
user2.setName("曹林与");
user2.setComment("我是一个永远你也猜不到的人!");
users.add(user2);
User user3=new User();
user3.setId(3);
user3.setName("宛萝琳");
user3.setComment("我是一个永远你也看不到的人!");
users.add(user3);
}
// public UserDaoImpl(){
// System.out.println("这是你的第二次调用!");
// }
@Override
public List<User> findAll() {
System.out.println("这是你的第一次调用findAll!");
return users;
}
@Override
public int deleteUser(int id) {
System.out.println("这是你的第一次调用deleteUser!");
int i=0;
for (User u:users) {
if(id==u.getId()){
users.remove(u);
i=1;
break;
}
}
return i;
}
@Override
public int addUser(User user) {
System.out.println("这是你的第一次调用addUser!");
int i=0;
if(user!=null){
users.add(user);
i=1;
}
return i;
}
@Override
public int updateUser(User user){
System.out.println("这是你的第一次调用updateUser!");
int i=0;
for (User u:users) {
if(user.getId()==u.getId()){
u.setName(user.getName());
u.setComment(user.getComment());
i=1;
}
}
return i;
}
@Override
public User findById(int id) {
System.out.println("这是你的第一次调用findById!");
User user=null;
for (User u:users) {
if(id==u.getId()){
user=u;
}
}
return user;
}
}
config层
MyKeyGenerator
package com.my.config;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
@Configuration
public class MyKeyGenerator {
@Bean("idGenerator")
public KeyGenerator idGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(params[0].toString());
return sb.toString();
}
};
}
}
service层
UserService
package com.my.service;
import com.my.pojo.User;
import java.util.List;
public interface UserService {
public List<User> findAll();
public int updateUser(User user);
public int deleteUser(int id);
public User findById(int id);
public int addUser(User user);
}
UserServiceImpl
package com.my.service;
import com.my.dao.UserDao;
import com.my.dao.UserDaoImpl;
import com.my.pojo.User;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@CacheConfig(cacheNames = "user") //{"user",“people”}指定多个命名空间
public class UserServiceImpl implements UserService{
private UserDao userDao;
public UserServiceImpl(){
userDao=new UserDaoImpl();
}
@Override
@Cacheable(key = "'all'") //将数据保存在缓存数据key为all上
public List<User> findAll() {
return userDao.findAll();
}
@Override
@CachePut(key = "#a0") //操作的是缓存,不是数据库
public int updateUser(User user) {
return userDao.updateUser(user);
}
@Override
@CacheEvict(key = "#id") //操作的是缓存,不是数据库
public int deleteUser(int id) {
return userDao.deleteUser(id);
}
@Override
// @Cacheable(cacheNames = "user",key = "#result",unless = "#result==null") 报错#result可能为null
@Cacheable(cacheNames = "user",keyGenerator = "idGenerator")//自己写个config解决key生成器
public User findById(int id) {
return userDao.findById(id);
}
@Override
@Caching(cacheable = {
@Cacheable(cacheNames = "user",key = "#a0")
},
put = {
@CachePut(cacheNames = "user",key = "#a0")//put 不管怎样都会访问数据库
})
public int addUser(User user) {
return userDao.addUser(user);
}
}
controller层
UserController
package com.my.controller;
import com.my.pojo.User;
import com.my.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
//查询所有user
@RequestMapping("/all")
public String findAll(Model model){
List<User> userList=userService.findAll();
model.addAttribute("users",userList);
System.out.println("hello");
return "list";
}
@ResponseBody
@RequestMapping("/del")
public String deleteUser(int id){
int i=userService.deleteUser(id);
System.out.println(i>0?"del ok":"del no");
return "del调用";
}
@ResponseBody
@RequestMapping("/upd")
public String updateUser(User user){
int i=userService.updateUser(user);
System.out.println(i>0?"ok":"no");
return user.toString();
}
@ResponseBody
@RequestMapping("/byId")
public String findById(int id){
User user=userService.findById(id);
System.out.println(user.toString());
return user.toString();
}
@ResponseBody
@RequestMapping("/add")
public String addUser(User user){
int i=userService.addUser(user);
System.out.println(i>0?"ok":"no");
return "hello";
}
}
主启动器
MyApplication
package com.my;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
页面
list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<!-- <link rel="SHORTCUT ICON" href="aa.ico"/>-->
<title>学生列表</title>
</head>
<body>
<div style="text-align: center;margin:0 auto" >
<div style="text-align: center">
<h3>列表</h3>
</div>
<div style="padding-left: 800px"><a th:href="@{#}" style="text-decoration: none; border: 1px solid #e8e8e8">添加</a></div>
<div>
<table border="1">
<thead>
<tr style="text-align: center">
<th style="width: 100px">id</th>
<th style="width: 100px">姓名</th>
<th style="width: 600px">评价</th>
<th style="width: 100px">操作</th>
</tr>
</thead>
<tbody>
<tr style="text-align: center" th:each="u:${users}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
<td th:text="${u.comment}"></td>
<td>
<a class="btn btn-primary" th:href="@{/upd/}+${u.id}" style="text-decoration: none">编辑</a>||
<a class="btn btn-warning" th:href="@{/delete/}+${u.id}" style="text-decoration: none">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
![](https://img-blog.csdnimg.cn/0aa7cec67ad1427c905833dfca227035.png)
![](https://img-blog.csdnimg.cn/ba78f46c4a7a4002a8575914c094fc56.png)
![](https://img-blog.csdnimg.cn/3557c8a268cd4ca588d9b8f0f9dfc964.png)
关于我的测试效果
@CacheConfig(cacheNames = "user")
![](https://img-blog.csdnimg.cn/fb767be0e1dc4e4e80bebea466143266.png)
看到出“这是你的第一次调用addUser!”这就话就只有依次,"hello"有两次,第一加载+刷新了一次。
![](https://img-blog.csdnimg.cn/473a762b547440b1a94346aa5ec591ba.png)
看到出”这是你的第一次调用deleteUser!“,有两次,因为我刷新了一次加上执行一次,并且@CacheEvict注解,它会先执行方法,再会清除缓存,”hello“有一次,因为我调用了all,根据结果可看出缓存删除成功。
![](https://img-blog.csdnimg.cn/237d6ff48956402ca8ea5fad3de81bc9.png)
@CachePut与@CacheEvict一样不管怎样都会先执行方法,然后在对缓存修改。
@Caching(cacheable = {
@Cacheable(cacheNames = "user",key = "#a0")
},
put = {
@CachePut(cacheNames = "user",key = "#a0")//put 不管怎样都会访问
})
@Cacheable注解+@CachePut注解
总结:明白缓存注解是对谁操作,不是数据库中数据,而是缓存的数据。这里没有提到缓存的cacheNames\key\unless\keyGenerator等及缓存数据结构等,这些需要自己找资料。我这里只是简单使用、浅学。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)