springboot-cache

springboot-cache介绍

  • 注解概念
名称释义
@Cacheable主要针对方法配置,能够根据方法的请求参数对其进行缓存
@CacheEvict清空缓存
@CachePut保证方法被调用,又希望结果被缓存。 与@Cacheable区别在于是否每次都调用方法,常用于更新
@EnableCaching开启基于注解的缓存
@CacheConfig统一配置本类的缓存注解的属性
  • 主要参数
名称释义
value缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写, 如果不指定,则缺省按照方法的所有参数进行组合 例如: @Cacheable(value=”testcache”,key=”#id”)
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false, 只有为 true 才进行缓存/清除缓存 例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
unless否定缓存。当条件结果为TRUE时,就不会缓存。 @Cacheable(value=”testcache”,unless=”#userName.length()>2”)
allEntries (@CacheEvict )是否清空所有缓存内容,缺省为 false,如果指定为 true, 则方法调用后将立即清空所有缓存 例如: @CachEvict(value=”testcache”,allEntries=true)
beforeInvocation (@CacheEvict)是否在方法执行前就清空,缺省为 false,如果指定为 true, 则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法 执行抛出异常,则不会清空缓存 例如: @CachEvict(value=”testcache”,beforeInvocation=true)
  • SqEL上下文数据
名称位置描述示例
methodNameroot对象当前被调用的方法名#root.methodname
methodroot对象当前被调用的方法#root.method.name
targetroot对象当前被调用的目标对象实例#root.target
targetClassroot对象当前被调用的目标对象的类#root.targetClass
argsroot对象当前被调用的方法的参数列表#root.args[0]
cachesroot对象当前方法调用使用的缓存列表#root.caches[0].name
Argument Name执行上下文当前被调用的方法的参数,如findArtisan(Artisan artisan),可以通过#artsian.id获得参数#artsian.id
result执行上下文方法执行后的返回值(仅当方法执行后的判断有效,如 unlesscacheEvict的beforeInvocation=false)

搭建环境

  • 添加依赖如下:
<?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.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-cache</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  • 创建User类:
package com.example.springbootcache.bean;

import javax.persistence.*;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column
    private String password;

    public User() {
    }

    public User(Long id, String userName, String password) {
        this.id = id;
        this.userName = userName;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long 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;
    }
}

  • 配置数据库及JPA
server:
  port: 8081

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/jpa?characterEncoding=utf8&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
  • 创建UserRepository:
package com.example.springbootcache.repository;

import com.example.springbootcache.bean.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

  • 创建UserController:
package com.example.springbootcache.controller;
import	java.util.Optional;

import com.example.springbootcache.bean.User;
import com.example.springbootcache.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/saveUser")
    @CachePut(value = "user", key = "#id")
    public User saveUser(Long id, String userName, String password) {
        User user = new User(id, userName, password);
        userRepository.save(user);
        return user;
    }

    @GetMapping("/queryUser")
    @Cacheable(value = "user", key = "#id")
    public Optional<User> queryUser(Long id){
        return userRepository.findById(id);
    }

    @GetMapping("/deleteUser")
    @CacheEvict(value = "user", key = "#id")
    public String deleteUser(Long id){
        userRepository.deleteById(id);
        return "success";
    }

    @GetMapping("/deleteCache")
    @CacheEvict(value = "user", allEntries = true)
    public void deleteCache(){
    }
}

运行测试

  • 保存一条数据,查看控制台是否有sql,如果有说明注解生效
    http://localhost:8081/saveUser?id=1&userName=aaa&password=123
  • 查询数据, 查看控制台是否有sql,如果没有说明注解生效,直接再数据库中插入一条数据,然后查询,控制台有sql语句,再查询一次,控制台没有sql,说明缓存生效
    http://localhost:8081/queryUser?id=1
  • 删除数据, 然后查询,控制台有sql语句,说明删除缓存生效
    http://localhost:8081/deleteUser?id=1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot中整合Ehcache缓存,需要进行以下几个步骤: 1. 添加Ehcache依赖 在pom.xml文件中添加Ehcache依赖: ``` <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> ``` 2. 配置Ehcache缓存 在application.yml(或application.properties)文件中配置Ehcache缓存: ``` spring: cache: type: ehcache ehcache: config: classpath:ehcache.xml ``` 其中,`spring.cache.type`属性指定使用的缓存类型为Ehcache,`ehcache.config`属性指定Ehcache配置文件的路径(在classpath下)。 3. 编写Ehcache配置文件 在classpath下创建`ehcache.xml`文件,配置Ehcache缓存的相关信息: ``` <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" transactionalMode="off"> </defaultCache> <cache name="userCache" maxEntriesLocalHeap="1000" maxEntriesLocalDisk="10000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> </cache> </ehcache> ``` 其中,`defaultCache`为默认缓存配置,`cache`为自定义缓存配置。 4. 在代码中使用缓存 在需要使用缓存的方法上添加`@Cacheable`注解,指定缓存名称和缓存key: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override @Cacheable(value = "userCache", key = "#id") public User getUserById(Integer id) { return userDao.getUserById(id); } // ... } ``` 其中,`value`属性指定缓存名称,`key`属性为缓存key表达式,可以使用Spring表达式语言(SpEL)进行动态表达。 以上就是在Spring Boot中整合Ehcache缓存的步骤,通过使用Ehcache缓存可以有效地提高应用程序的性能和响应速度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈攻城狮攻略者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值