springboot项目@Cacheable缓存注解的应用

1.环境准备

基本的目录结构

数据库准备

创建数据库的sql语句

/*
 Navicat Premium Data Transfer

 Source Server         : localhost_3306
 Source Server Type    : MySQL
 Source Server Version : 80026
 Source Host           : localhost:3306
 Source Schema         : newsmanagersystem

 Target Server Type    : MySQL
 Target Server Version : 80026
 File Encoding         : 65001

 Date: 11/01/2022 15:12:34
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for comments
-- ----------------------------
DROP TABLE IF EXISTS `comments`;
CREATE TABLE `comments`  (
  `cid` int NOT NULL AUTO_INCREMENT,
  `cnid` int NOT NULL,
  `ccontent` varchar(3000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `cdate` datetime(0) NOT NULL,
  `cip` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `cauthor` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`cid`) USING BTREE,
  INDEX `CIN_NID`(`cnid`) USING BTREE,
  CONSTRAINT `CIN_NID` FOREIGN KEY (`cnid`) REFERENCES `news` (`nid`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 53 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for news
-- ----------------------------
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news`  (
  `nid` int NOT NULL AUTO_INCREMENT,
  `ntid` int NOT NULL,
  `ntitle` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `nauthor` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `ncreateDate` datetime(0) NULL DEFAULT NULL,
  `npicPath` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
  `ncontent` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `nmodifyDate` datetime(0) NULL DEFAULT NULL,
  `nsummary` varchar(4000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`nid`) USING BTREE,
  INDEX `NEWS_TOPIC`(`ntid`) USING BTREE,
  CONSTRAINT `NEWS_TOPIC` FOREIGN KEY (`ntid`) REFERENCES `topic` (`tid`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 196 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for news_users
-- ----------------------------
DROP TABLE IF EXISTS `news_users`;
CREATE TABLE `news_users`  (
  `uid` int NOT NULL AUTO_INCREMENT,
  `uname` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `u_pwd` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`uid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for topic
-- ----------------------------
DROP TABLE IF EXISTS `topic`;
CREATE TABLE `topic`  (
  `tid` int NOT NULL AUTO_INCREMENT,
  `tname` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`tid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 36 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

user实体类

package com.dfp.springboot_cache.bean;
import java.io.Serializable;
public class Users implements Serializable {

private static final long serialVersionUID=1L;


    //编号
    private Integer uid;

    private String uname;

    private String upwd;


    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUpwd() {
        return upwd;
    }

    public void setUpwd(String upwd) {
        this.upwd = upwd;
    }

    @Override
    public String toString() {
        return "Users{" +
        "uid=" + uid +
        ", uname=" + uname +
        ", upwd=" + upwd +
        "}";
    }
}

关于user的mapper操作数据库基于注解的方式

package com.dfp.springboot_cache.Mapper;

import com.dfp.springboot_cache.bean.Users;
import org.apache.catalina.User;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UsersMapper {
    @Select("select * from news_users where uid=#{id}")
    public Users getUsersById(Integer id);

    @Update("update news_users set uname=#{uname},upwd=#{upwd} where by uid=#{id}")
    public void updateUsersById(Integer id);

    @Delete("delete from news_users where uid=#{uid}")
    public void deleteUsersById(Integer id);

    @Insert("insert into news_users(uname,upwd) value(#{uname},#{upwd})")
    public void insertUsers(Users users);

}

userService

package com.dfp.springboot_cache.Service;

import com.dfp.springboot_cache.Mapper.UsersMapper;
import com.dfp.springboot_cache.bean.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    UsersMapper usersMapper;
    public Users getUserById(int id){
        System.out.println("查询"+id+"员工");
        Users users=usersMapper.getUsersById(id);
        return users;
    }
}

控制类

package com.dfp.springboot_cache;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching//开启基于注解的缓存
@MapperScan(value = "com.dfp.springboot_cache.Mapper")
@SpringBootApplication
public class SpringbootCaCheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootCaCheApplication.class, args);
    }

}

2.运行项目测试

 我们多次执行项目我们发现每一次执行相同步骤的时候回多次调用同一个方法让后查询数据库

如果面临大型项目的时候我们多次访问同一个数据的时候回让系统变的很慢

这个时候我们就引入缓存,让程序执行同一个方法的时候第一次执行的时候记录结果,再次执行的时候无需调用方法

3.@Cacheable缓存注解的应用

引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

或者在创建项目的时候选中这个模块

 我是直接选中的模块

然后我们要修改2处位置

 控制类加入注解

 service逻辑层加入注解一些基本运用方法我已经写在注解中

4.缓存测试

 我先按顺序查询了1/2/3/4的记录最后返回来查询2发现控制台不在打印查询x员工的语句

因为再次进入没有调用service层的方法了

5.缓存原理及其运行流程

@Cacheable

1、方法运行之前,先去查询Cache(缓仔组件),按照cacheNames指定的名字获取;
(CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。

2.去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key
3、1没有查到缓存就调用目标方法;
4、将目标方法返回的结果,放进缓存中
@Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,如果没有就运行方法并将结果放入缓存;

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值