SpringBoot与SpringCache概念用法大全

 更新时间:2022年02月11日 16:31:36   作者:#Hideonbush  
这篇文章主要介绍了SpringBoot与SpringCache的概念及基本用法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1.SpringCache的概念

首先我们知道jpa,jdbc这些东西都是一些规范,比如jdbc,要要连接到数据库,都是需要用到数据库连接,预处理,结果集这三个对象,无论是连接到mysql还是oracle都是需要用到这个三个对象的,这是一种规范,而SpringCache是一种作为缓存的规范,具体实现有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注解时

6.2)userservice加@Cacheable注解后,发现sevice中的方法只调用了一次

6.3)在redis中也可以看到缓存中有数据,key为定义好的cacheNames+::+方法的参数

2.2 .SpringCache自定义缓存key

1.SpringCache默认使用cacheNames和方法中的参数结合组成key的,那么如果有多个参数呢?它又是如何组成key的呢?我们可以指定key吗?

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)测试

2.3 .SpringCache更新缓存

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

2.4 .SpringCache清空缓存

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

2.测试

2.5 .SpringCache其他用法

1.@Caching注解,可以组合多个注解

2.@CacheConfig注解

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的文章就介绍到这了,更多相关SpringBoot与SpringCache内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java ZooKeeper分布式锁实现图解

    Java ZooKeeper分布式锁实现图解

    ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等
    2022-03-03
  • java文件下载设置中文名称的实例(response.addHeader)

    java文件下载设置中文名称的实例(response.addHeader)

    下面小编就为大家分享一篇java文件下载设置中文名称的实例(response.addHeader),具有很好的参考价值,希望对大家有所帮助
    2017-12-12
  • Scala数据库连接池的简单实现

    Scala数据库连接池的简单实现

    本文主要介绍了Scala数据库连接池的简单实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • Java判断多个时间段是否重合的方法小结

    Java判断多个时间段是否重合的方法小结

    这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-02-02
  • 用Java轻松读取Word文档内容的常用方法

    用Java轻松读取Word文档内容的常用方法

    这篇文章主要介绍了用Java轻松读取Word文档内容的常用方法,对于doc格式使用Apache POI库中的HWPFDocument和WordExtractor类,对于docx格式使用XWPFDocument类,并通过遍历段落和文本运行对象来提取文本内容,需要的朋友可以参考下
    2025-03-03
  • Java spring定时任务详解

    Java spring定时任务详解

    这篇文章主要为大家详细介绍了Spring定时任务,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-10-10
  • Spring MVC 404 Not Found无错误日志的解决方法

    Spring MVC 404 Not Found无错误日志的解决方法

    这篇文章主要为大家详细介绍了Spring MVC 404 Not Found无错误日志的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12
  • SpringBoot连接Nacos集群报400问题及完美解决方法

    SpringBoot连接Nacos集群报400问题及完美解决方法

    这篇文章主要介绍了解决SpringBoot连接Nacos集群报400问题 ,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-02-02
  • Java文件批量重命名批量提取特定类型文件

    Java文件批量重命名批量提取特定类型文件

    这篇文章主要介绍了Java文件批量重命名批量提取特定类型文件的相关资料
    2016-08-08
  • Springboot自动加载配置的原理解析

    Springboot自动加载配置的原理解析

    Springboot遵循“约定优于配置”的原则,使用注解对一些常规的配置项做默认配置,减少或不使用xml配置,让你的项目快速运行起来,这篇文章主要给大家介绍了关于Springboot自动加载配置原理的相关资料,需要的朋友可以参考下
    2021-10-10

最新评论