SpringBoot缓存注解使用(无数据库操作)

2023-05-16

SpringBoot缓存注解使用(无数据库操作)

缓存注解介绍

  1. @EnableCaching注解:开启注解缓存的支持

  2. @Cacheable注解:对方法的查询结果进行缓存

  3. @CachePut注解:更新缓存

  4. @CacheEvict注解:删除缓存

  5. @Caching注解:处理复杂缓存

  6. @CacheConfig注解:统筹管理@CachePut、@CacheEvict、@Caching

项目层次结构

 

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>  

 

  • 这段没有时间写,所有页面只有个,其他功能不完整。

  • 测试时直接在url上面操作,如下:--->(在后就是返回all,可以改我那controller中方法返回值,直接到all接口,就不用重新输入url)

 

 

  • 要看自己缓存是否变化,根据我提供的代码,因为我在dao层的方法中,输入了 System.out.println("这是你的第一次调用addUser!")。是这句话来判断是否有调用缓存。

关于我的测试效果

  • @CacheConfig注解--->管理


@CacheConfig(cacheNames = "user")  
  • 查询全部--->Cacheable注解使用

 

看到出“这是你的第一次调用addUser!”这就话就只有依次,"hello"有两次,第一加载+刷新了一次。

  • 删除--->@CacheEvict注解使用

 

看到出”这是你的第一次调用deleteUser!“,有两次,因为我刷新了一次加上执行一次,并且@CacheEvict注解,它会先执行方法,再会清除缓存,”hello“有一次,因为我调用了all,根据结果可看出缓存删除成功。

  • 更新--->@CachePut注解使用

 

@CachePut与@CacheEvict一样不管怎样都会先执行方法,然后在对缓存修改。

  • @Caching注解使用

@Caching(cacheable = {
         @Cacheable(cacheNames = "user",key = "#a0")
 },
put = {
         @CachePut(cacheNames = "user",key = "#a0")//put 不管怎样都会访问
})

@Cacheable注解+@CachePut注解

总结:明白缓存注解是对谁操作,不是数据库中数据,而是缓存的数据。这里没有提到缓存的cacheNames\key\unless\keyGenerator等及缓存数据结构等,这些需要自己找资料。我这里只是简单使用、浅学。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot缓存注解使用(无数据库操作) 的相关文章

随机推荐

  • swagger被拦截器拦截

    配置swagger文档 xff0c 被拦截器拦截不能使用 拦截器中添加以下配置 xff0c 适当修改即可使用 重写addInterceptors registry addInterceptor new UserInterceptor add
  • JAVA之JDBC连接数据库

    前景说明 xff1a 在我们刚开始使用数据库的时候 xff0c 发现只能在mysql编辑器里面使用sql语句来完成对数据库的操作 xff0c 那我们怎么来通过Java来操控数据库呢 xff1f 这个时候就有了JDBC的出现 1 什么是JDB
  • Css margin 和 float浮动

    1 浮动 定义 浮动是css里面布局最多的一个属性 xff0c 也是很重要的一个属性 float xff1a 表示浮动的意思 它有四个值 none 表示不浮动 xff0c 默认right xff1a 表示右浮动left 表示左浮动 floa
  • Java Servlet组件

    1 什么是Servlet xff1f 从广义上来讲 xff0c Servlet规范是Sun公司制定的一套技术标准 xff0c 包含与Web应用相关的一系列接口 xff0c 是Web应用实现方式的宏观解决方案 而具体的Servlet容器负责提
  • JAVA 之 Ajax

    1 什么是Ajax xff1f AJAX xff08 Asynchronous Javascript And XML xff09 翻译成中文就是 异步Javascript和XML 即是用Javascript语言与服务器进行异步交互 xff0
  • Servlet 的Request和Response

    1 Request和Response概述 1 Request 获取请求数据 浏览器会发送HTTP请求到后台服务器 Tomcat HTTP的请求中会包含很多请求数据 请求行 43 请求头 43 请求体 后台服务器 Tomcat 会对HTTP请
  • 链接标签的使用

    什么是链接 xff1f 链接相当于是一个传送门 xff0c 点击链接就可以从该页面 xff0c 跳转到其他页面 xff0c 或者从该页面跳转到该页面的其他地方 链接的表现形式有哪些 xff1f 链接可以 表现为文字 xff0c 图片 xff
  • 报错 java: 程序包org.apache.ibatis.annotations不存在

    今天在使用mybatis运行项目时 xff0c 项目忽然报错了 xff0c 检查了自己的pom xml文件也没有问题 xff0c 报错情况如图 xff1a 在网上找了一大堆方法 xff0c 都没有解决问题 xff0c 这里附上一个网上的常用
  • spring框架

    文章内容 介绍spring框架 为什么要使用spring框架 如何使用spring IOC控制反转 1 介绍spring框架 1 spring是一个轻量级开源的JAVAEE框架 2 Spring提高了IOC和AOP IOC 控制反转 把创建
  • Ubuntu忘记密码怎么办 如何重置Ubuntu登入密码

    1 首先重新启动Ubuntu系统 xff0c 然后快速按下shift键 xff0c 以调出grub启动菜单 2 在这里我们选择第二个 xff08 Ubuntu高级选项 xff09 xff0c 选中后按下Enter键 3 选择第二个recov
  • 快速掌握e语言,以js语言对比,快速了解掌握。

    易语言 xff0c 怎么调试输出 xff0c 查看内容 在js语言里 xff0c 弹窗是 alert 在易语言里 xff0c 弹窗是 信息框 弹出显示内容 0 标题 在js语言里 xff0c 调试输出是 console log 在易语言里
  • java 实现Comparable接口排序,升序、降序、倒叙

    本人由于项目开发中需要对查询结果list进行排序 xff0c 这里根据的是每一个对象中的创建时间降序排序 本人讲解不深 xff0c 只实现目的 xff0c 如需理解原理还需查阅更深的资料 1 实现的效果 2 创建排序的对象 package
  • gitbash不能粘贴

    点击鼠标滚轮或者shift 43 ins
  • Hive安装与配置常见问题解决

    欢 43 迎使用Markdown编辑器 提示 xff1a 文章写完后 xff0c 目录可以自动生成 xff0c 如何生成可参考右边的帮助文档 目录 前言一 Hive是什么 xff1f 二 安装步骤1 引入jar包2 配置步骤1 hive s
  • 【Linux】生产者消费者模型

    文章目录 1 生产者消费者模型1 1生产者消费者模型的特点1 2生产者消费者模型的原则1 3生产者消费者模型的优点 2 基于阻塞队列的生产者消费者模型2 1如何理解生产者消费者模型的并发 xff1f 3 信号量3 1信号量接口3 2基于环形
  • Ubuntu设置允许root用户登录

    Ubuntu激活root用户 sudo passwd root 设置root密码 设置允许root通过ssh默认登录 vim etc ssh sshd config root权限编辑 PermitRootLogin yes 在第一行添加内容
  • python编写程序统计一元人民币换成一分、两分和五分的所有兑换方案个数(用while循环)

    a 61 int input 34 输入钱数 xff08 单位 xff1a 元 xff09 34 e 61 a 100 count 61 0 i 61 1 while i lt e 5 43 1 i 43 61 1 b 61 e 5 i 2
  • springboot简易整合mybatis

    SpringBoot整合Mybatis篇 实现单表mybatis整合 准备sql 创建数据库 create database if not exists 96 mybatis 96 修改数据库默认字节编码 alter database 96
  • Springboot+PageHelper实现分页(前后端简单展示)

    Springboot 43 PageHelper实现分页 前后端简单展示 创建表及赋值 创建表 DROP TABLE IF EXISTS 96 page learn 96 CREATE TABLE 96 page learn 96 96 i
  • SpringBoot缓存注解使用(无数据库操作)

    SpringBoot缓存注解使用 无数据库操作 缓存注解介绍 64 EnableCaching注解 xff1a 开启注解缓存的支持 64 Cacheable注解 xff1a 对方法的查询结果进行缓存 64 CachePut注解 xff1a