溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot與SpringCache概念是什么

發(fā)布時間:2022-02-14 09:50:17 來源:億速云 閱讀:90 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)SpringBoot與SpringCache概念是什么的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

    1.SpringCache的概念

    首先我們知道jpa,jdbc這些東西都是一些規(guī)范,比如jdbc,要要連接到數(shù)據(jù)庫,都是需要用到數(shù)據(jù)庫連接,預(yù)處理,結(jié)果集這三個對象,無論是連接到mysql還是oracle都是需要用到這個三個對象的,這是一種規(guī)范,而SpringCache是一種作為緩存的規(guī)范,具體實現(xiàn)有redis,EhCahe等

    2.SpringCache用法(redis版)

    2.1 .SpringCache基本用法

    1.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 https://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.6.3</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.yl</groupId>
        <artifactId>cache_redis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>cache_redis</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>11</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <artifactId>spring-boot-starter-web</artifactId>
    
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>

    2.application.properties

    # redis的配置
    spring.redis.host=192.168.244.135
    spring.redis.port=6379
    spring.redis.password=root123

    3.實體類

    package com.yl.cache_redis.domain;
    import java.io.Serializable;
    public class User implements Serializable {
        private Integer id;
        private String username;
        private String password;
        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 getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }

    4.service

    package com.yl.cache_redis;
    
    import com.yl.cache_redis.domain.User;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    @Service
    public class UserService {
        @Cacheable(cacheNames = "u1") //這個注解作用就是將方法的返回值存到緩存中
        public User getUserById(Integer id) {
            System.out.println("getUserById:" + id);
            User user = new User();
            user.setId(id);
            user.setUsername("root");
            user.setPassword("root");
            return user;
        }
    }

    5.主程序,加上開啟緩存的注解

    package com.yl.cache_redis;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    @SpringBootApplication
    @EnableCaching //開啟緩存功能
    public class CacheRedisApplication {
        public static void main(String[] args) {
            SpringApplication.run(CacheRedisApplication.class, args);
        }
    }

    6.測試

    6.1)userservice沒加@Cacheable注解時

    SpringBoot與SpringCache概念是什么

    6.2)userservice加@Cacheable注解后,發(fā)現(xiàn)sevice中的方法只調(diào)用了一次

    SpringBoot與SpringCache概念是什么

    6.3)在redis中也可以看到緩存中有數(shù)據(jù),key為定義好的cacheNames+::+方法的參數(shù)

    SpringBoot與SpringCache概念是什么

    2.2 .SpringCache自定義緩存key

    1.SpringCache默認(rèn)使用cacheNames和方法中的參數(shù)結(jié)合組成key的,那么如果有多個參數(shù)呢?它又是如何組成key的呢?我們可以指定key嗎?

    SpringBoot與SpringCache概念是什么

    SpringBoot與SpringCache概念是什么

    SpringBoot與SpringCache概念是什么

    2.如何自定義key呢?

    1)自定義key

    package com.yl.cache_redis;
    
    import org.springframework.cache.interceptor.KeyGenerator;
    import org.springframework.stereotype.Component;
    import java.lang.reflect.Method;
    import java.util.Arrays;
    @Component
    public class MyKeyGenerator implements KeyGenerator {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            return target.toString() + ":" + method.getName() + ":" + Arrays.toString(params);
        }
    }

    2)測試

    SpringBoot與SpringCache概念是什么

    SpringBoot與SpringCache概念是什么

    SpringBoot與SpringCache概念是什么

    2.3 .SpringCache更新緩存

    1.使用@CachePut注解來更新,注意:@CachePut中的key要和@Cacheable中的key一樣,否則更新不了!

    SpringBoot與SpringCache概念是什么

    SpringBoot與SpringCache概念是什么

    2.4 .SpringCache清空緩存

    1.使用@CacheEvict注解,主要key和要@Cacheable中的key一致

    SpringBoot與SpringCache概念是什么

    2.測試

    SpringBoot與SpringCache概念是什么

    2.5 .SpringCache其他用法

    1.@Caching注解,可以組合多個注解

    SpringBoot與SpringCache概念是什么

    2.@CacheConfig注解

    SpringBoot與SpringCache概念是什么

    3.SpringCache用法(EhCache版)

    1.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 https://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.6.3</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.yl</groupId>
        <artifactId>ehcache</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>ehcache</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>11</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>
                <artifactId>spring-boot-starter-web</artifactId>
    
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache</artifactId>
                <version>2.10.6</version>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>

    2.實體類

    package com.yl.ehcache.model;
    import java.io.Serializable;
    public class User implements Serializable {
        private Integer id;
        private String username;
        private String password;
        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 getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }

    3.service

    package com.yl.ehcache.service;
    
    import com.yl.ehcache.model.User;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    @Service
    public class UserService {
        @Cacheable(cacheNames = "user")
        public User getUserById(Integer id) {
            System.out.println("getUserById()...");
            User user = new User();
            user.setId(id);
            user.setUsername("root");
            user.setPassword("root");
            return user;
        }
        @CacheEvict(cacheNames = "user")
        public void delete(Integer id) {
            System.out.println("delete");
    }

    4.主程序

    package com.yl.ehcache;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    @SpringBootApplication
    @EnableCaching
    public class EhcacheApplication {
        public static void main(String[] args) {
            SpringApplication.run(EhcacheApplication.class, args);
        }
    }

    5.ehcache.xml

    <ehcache>
        <diskStore path="java.io.tmpdir/shiro-spring-sample"/>
        <defaultCache
                maxElementsInMemory = "1000"
                eternal = "false"
                timeToIdleSeconds = "120"
                timeToLiveSeconds = "120"
                overflowToDisk = "false"
                diskPersistent = "false"
                diskExpiryThreadIntervalSeconds = "120"/>
        <cache name = "user"
               maxElementsInMemory = "1000"
               eternal = "false"
               overflowToDisk = "true"
               diskPersistent = "true"
               diskExpiryThreadIntervalSeconds = "600"/>
    </ehcache>

    6.測試

    SpringBoot與SpringCache概念是什么

    感謝各位的閱讀!關(guān)于“SpringBoot與SpringCache概念是什么”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI