欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Cache框架應(yīng)用介紹

 更新時(shí)間:2022年09月14日 17:13:50   作者:杼蛘  
我們一定聽說(shuō)過(guò)"緩存無(wú)敵"的話,特別是在大型互聯(lián)網(wǎng)公司,"查多寫少"的場(chǎng)景屢見不鮮。Spring Cache是作用在方法上的,其核心思想是,當(dāng)我們?cè)谡{(diào)用一個(gè)緩存方法時(shí)會(huì)把該方法參數(shù)和返回結(jié)果作為一個(gè)鍵值對(duì)存在緩存中

介紹

Spring Cache是一個(gè)框架,實(shí)現(xiàn)了基于注解的緩存功能,只需要簡(jiǎn)單地加一個(gè)注解,就能實(shí)現(xiàn)緩存功能。

Spring Cache提供了一層抽象,底層可以切換不同的cache實(shí)現(xiàn)。具體就是通過(guò)CacheManager接口來(lái)統(tǒng)一不同的緩存技術(shù)。

CacheManager是Spring提供的各種緩存技術(shù)抽象接口。

針對(duì)不同的緩存技術(shù)需要實(shí)現(xiàn)不同的CacheManager:

CacheManager描述
EhCacheCacheManager使用EhCache作為緩存技術(shù)
GuavaCacheManager使用Google的GuavaCache作為緩存技術(shù)
RedisCacheManager使用Redis作為緩存技術(shù)

常用注解

注解說(shuō)明
@EnableCaching開啟緩存注解功能
@Cacheable在方法執(zhí)行前spring先查看緩存中是否有數(shù)據(jù),如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒有數(shù)據(jù),調(diào)用方法并將方法返回值放到緩存中
@CachePut將方法的返回值放到緩存中
@CacheEvict將一條或多條數(shù)據(jù)從緩存中刪除

在Spring Boot項(xiàng)目中,使用緩存技術(shù)只需在項(xiàng)目中導(dǎo)入相關(guān)緩存技術(shù)的依賴包,并在啟動(dòng)類上使用@EnableCaching開啟緩存支持即可。

例如,使用Redis作為緩存技術(shù),只需要導(dǎo)入spring-boot-starter-data-redis的Maven坐標(biāo)即可。

實(shí)際測(cè)試

使用Spring Cache(默認(rèn)緩存ConcurrentMapCacheManager

創(chuàng)建Spring Boot項(xiàng)目,使用MybatisX插件生成對(duì)應(yīng)的mapper、service、實(shí)體類等,導(dǎo)入相關(guān)依賴,修改配置文件,創(chuàng)建數(shù)據(jù)庫(kù)

pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.itheima</groupId>
    <artifactId>cache_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.23</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.5</version>
            </plugin>
        </plugins>
    </build>
</project>

application.yml如下:

server:
  port: 8080
spring:
  application:
    #應(yīng)用的名稱,可選
    name: cache_demo
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: 123456
mybatis-plus:
  configuration:
    #在映射實(shí)體或者屬性時(shí),將數(shù)據(jù)庫(kù)中表名和字段名中的下劃線去掉,按照駝峰命名法映射
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: ASSIGN_ID

數(shù)據(jù)庫(kù)SQL如下:

/*
 Navicat Premium Data Transfer
 Source Server         : Aiw
 Source Server Type    : MySQL
 Source Server Version : 50528
 Source Host           : localhost:3306
 Source Schema         : cache_demo
 Target Server Type    : MySQL
 Target Server Version : 50528
 File Encoding         : 65001
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1568896554487369729, 'Aiw', 22, '湖北省');
SET FOREIGN_KEY_CHECKS = 1;

在啟動(dòng)類上添加@EnableCaching注解

package com.itheima;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@Slf4j
@SpringBootApplication
@EnableCaching  // 開啟緩存注解功能
public class CacheDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheDemoApplication.class,args);
        log.info("項(xiàng)目啟動(dòng)成功...");
    }
}

創(chuàng)建UserController

package com.itheima.controller;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private UserService userService;
    /**
     * CachePut:將方法返回值放入緩存
     * value:緩存的名稱,每個(gè)緩存名稱下面可以有多個(gè)key
     * key:緩存的key
     */
    @CachePut(value = "userCache", key = "#user.id")
    @PostMapping
    public User save(User user) {
        userService.save(user);
        return user;
    }
    /**
     * CacheEvict:清理指定緩存
     * value:緩存的名稱,每個(gè)緩存名稱下面可以有多個(gè)key
     * key:緩存的key
     */
    @CacheEvict(value = "userCache", key = "#p0")
    //@CacheEvict(value = "userCache",key = "#root.args[0]")
    //@CacheEvict(value = "userCache",key = "#id")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        userService.removeById(id);
    }
    //@CacheEvict(value = "userCache",key = "#p0.id")
    //@CacheEvict(value = "userCache",key = "#user.id")
    //@CacheEvict(value = "userCache",key = "#root.args[0].id")
    @CacheEvict(value = "userCache", key = "#result.id")
    @PutMapping
    public User update(User user) {
        userService.updateById(user);
        return user;
    }
    /**
     * Cacheable:在方法執(zhí)行前spring先查看緩存中是否有數(shù)據(jù),如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒有數(shù)據(jù),調(diào)用方法并將方法返回值放到緩存中
     * value:緩存的名稱,每個(gè)緩存名稱下面可以有多個(gè)key
     * key:緩存的key
     * condition:條件,滿足條件時(shí)才緩存數(shù)據(jù)
     * unless:滿足條件則不緩存
     */
    @Cacheable(value = "userCache", key = "#id", unless = "#result == null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id) {
        return userService.getById(id);
    }
    @Cacheable(value = "userCache", key = "#user.id + '_' + #user.name")
    @GetMapping("/list")
    public List<User> list(User user) {
        return userService.lambdaQuery()
                .eq(Objects.nonNull(user.getId()), User::getId, user.getId())
                .eq(Objects.nonNull(user.getName()), User::getName, user.getName())
                .list();
    }
}

以上不同寫法均等價(jià)

使用ApiPost進(jìn)行接口測(cè)試

打斷點(diǎn)調(diào)試,發(fā)送請(qǐng)求,可以看到已存入緩存

該緩存底層基于Map實(shí)現(xiàn),默認(rèn)ConcurrentHashMap基于內(nèi)存,重啟服務(wù)會(huì)清空緩存數(shù)據(jù)

使用Spring Cache(redis緩存RedisCacheManager

導(dǎo)入Maven坐標(biāo)

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

修改配置文件

server:
  port: 8080
spring:
  application:
    #應(yīng)用的名稱,可選
    name: cache_demo
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: 123456
  redis:
    host: localhost
    port: 6379
#    password: root@123456
    database: 0
  cache:
    redis:
      time-to-live: 1800000 #設(shè)置緩存過(guò)期時(shí)間(單位:秒),可選
mybatis-plus:
  configuration:
    #在映射實(shí)體或者屬性時(shí),將數(shù)據(jù)庫(kù)中表名和字段名中的下劃線去掉,按照駝峰命名法映射
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: ASSIGN_ID

啟動(dòng)項(xiàng)目,再次請(qǐng)求接口

啟動(dòng)redis命令行窗口,查看

當(dāng)請(qǐng)求不存在的id時(shí),不會(huì)執(zhí)行緩存操作(@Cacheable注解的unless條件起作用)

到此這篇關(guān)于Spring Cache框架應(yīng)用介紹的文章就介紹到這了,更多相關(guān)Spring Cache框架內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 利用maven deploy上傳本地jar至私服的方法

    利用maven deploy上傳本地jar至私服的方法

    這篇文章主要介紹了利用maven deploy上傳本地jar至私服的方法,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02
  • JDBC獲取元數(shù)據(jù)demo

    JDBC獲取元數(shù)據(jù)demo

    這篇文章主要為大家介紹了JDBC獲取元數(shù)據(jù)實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • xxl-job 帶參數(shù)執(zhí)行和高可用部署方法

    xxl-job 帶參數(shù)執(zhí)行和高可用部署方法

    這篇文章主要介紹了xxl-job 帶參數(shù)執(zhí)行和高可用部署,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • Java Socket通信(一)之客戶端程序 發(fā)送和接收數(shù)據(jù)

    Java Socket通信(一)之客戶端程序 發(fā)送和接收數(shù)據(jù)

    對(duì)于Socket通信簡(jiǎn)述,服務(wù)端往Socket的輸出流里面寫東西,客戶端就可以通過(guò)Socket的輸入流讀取對(duì)應(yīng)的內(nèi)容,Socket與Socket之間是雙向連通的,所以客戶端也可以往對(duì)應(yīng)的Socket輸出流里面寫東西,然后服務(wù)端對(duì)應(yīng)的Socket的輸入流就可以讀出對(duì)應(yīng)的內(nèi)容
    2016-03-03
  • java-spark中各種常用算子的寫法示例

    java-spark中各種常用算子的寫法示例

    這篇文章主要給大家介紹了關(guān)于java-spark中各種常用算子的寫法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-06-06
  • Java中使用WebSocket的幾種方式

    Java中使用WebSocket的幾種方式

    本文主要介紹了Java中使用WebSocket的幾種方式
    2024-06-06
  • 如何使用Idea中的 Deployment 實(shí)現(xiàn)打包自動(dòng)部署

    如何使用Idea中的 Deployment 實(shí)現(xiàn)打包自動(dòng)部署

    這篇文章主要介紹了使用Idea中的 Deployment 實(shí)現(xiàn)打包自動(dòng)部署,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-08-08
  • Java基礎(chǔ)教程之構(gòu)造器與方法重載

    Java基礎(chǔ)教程之構(gòu)造器與方法重載

    這篇文章主要介紹了Java基礎(chǔ)教程之構(gòu)造器與方法重載,構(gòu)造器可以初始化數(shù)據(jù)成員,還可以規(guī)定特定的操作,本文還對(duì)方法重載做了介紹,需要的朋友可以參考下
    2014-08-08
  • SpringMVC中@Valid不起效BindingResult讀取不到Error信息

    SpringMVC中@Valid不起效BindingResult讀取不到Error信息

    在寫SpringMVC項(xiàng)目時(shí),由于要對(duì)表單數(shù)據(jù)進(jìn)行校驗(yàn),需要使用@Valid進(jìn)行校驗(yàn),但是在進(jìn)行數(shù)據(jù)校驗(yàn)時(shí),BindingResult對(duì)象無(wú)法攔截非法表單數(shù)據(jù),result.hasErrors()無(wú)論怎么輸入都會(huì)返回false,本文詳細(xì)的介紹一下解決方法
    2021-09-09
  • Maven導(dǎo)入Junit4后在test中無(wú)法引用問題

    Maven導(dǎo)入Junit4后在test中無(wú)法引用問題

    在使用Maven進(jìn)行項(xiàng)目管理時(shí),可能會(huì)遇到導(dǎo)入依賴和打開項(xiàng)目結(jié)構(gòu)的問題,本文通過(guò)實(shí)際經(jīng)驗(yàn),提供了一些解決方法和技巧,希望能幫助遇到相同問題的開發(fā)者,此外,還鼓勵(lì)大家多多支持和分享個(gè)人經(jīng)驗(yàn),以便于共同進(jìn)步
    2024-10-10

最新評(píng)論