3年前 (2021-07-31)  相关技术 |   抢沙发  1040 
文章评分 0 次,平均分 0.0

昂贵的(CPU或I/O)绑定操作会降低系统的速度。缓存是提高系统性能的一种方法。在本文中,我们将演示如何使用Spring-Boot进行缓存。您可以使用caffeine作为spring框架缓存抽象之上的缓存提供者。

Maven依赖项

我们使用Maven来管理我们的项目依赖关系。首先,将以下依赖项添加到项目中。在本例中,我们使用com.github.ben-manes.caffee-caffee作为缓存提供程序。

<?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>
    <groupId>com.memorynotfound.springboot.caching</groupId>
    <artifactId>caffeine</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>Spring Boot - ${project.artifactId}</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring Framework Caching Support -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!-- caching provider -->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
    </dependencies>

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

</project>

Caffeine缓存服务示例

为了演示spring框架的缓存,我们编写了一个简单的服务,它将根据条件缓存结果。让我们从定义接口开始。

package com.memorynotfound.springboot;

public interface MusicService {

    String play(final String instrument);
}

以下服务使用@CacheConfig注释进行注释,并使用两个缓存目录和工具。play方法使用@Cacheable注释进行注释,并给定一个条件参数,这意味着当条件求值为true时,此方法的结果将在后续调用时被缓存。

package com.memorynotfound.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = {"directory", "instruments"})
public class MusicServiceIml implements MusicService {

    private static Logger log = LoggerFactory.getLogger(MusicServiceIml.class);

    @Cacheable(condition = "#instrument.equals('trombone')")
    public String play(String instrument) {
        log.info("Executing: " + this.getClass().getSimpleName() + ".play(\"" + instrument + "\");");
        return "paying " + instrument + "!";
    }

}

配置Caffeine缓存

我们使用application.yml文件配置咖啡因。我们可以通过将逗号分隔的列表附加到spring.cache.cache-names配置属性来创建缓存目录。我们可以使用spring.cache.caffee.spec配置属性定义自定义规范。

CaffeineSpec支持以下配置属性:

  • initialCapacity=[integer]:设置内部哈希表的最小总大小。在构建时提供足够大的估计值,避免了以后需要昂贵的调整大小操作,但是不必要地将此值设置为高值会浪费内存。
  • maximumSize=[long]:指定缓存可能包含的最大条目数。请注意,缓存可能会在超过此限制之前逐出条目,或在逐出时临时超过阈值。此功能不能与maximumWeight一起使用。
  • maximumWeight=[long]:指定缓存可能包含的项的最大权重。请注意,缓存可能会在超过此限制之前逐出条目,或在逐出时临时超过阈值。此功能不能与maximumSize一起使用。
  • expireAfterAccess=[duration]:指定在创建条目后经过固定的持续时间后,应自动从缓存中删除每个条目。
  • expireAfterWrite=[duration]:指定在创建条目或最新替换其值后经过固定的持续时间后,应自动从缓存中删除每个条目。
  • refreshAfterWrite=[duration]:指定活动项在创建后经过一个固定的持续时间或其值的最近一次替换后,可以自动刷新。

持续时间由整数表示,后跟“d”、“h”、“m”或“s”中的一个,分别表示天、小时、分钟或秒。当前没有以毫秒、微秒或纳秒为单位请求过期的语法。

spring:
    cache:
        cache-names: instruments, directory
        caffeine:
            spec: maximumSize=500, expireAfterAccess=30s

logging:
  pattern:
    console: "%-5level - %msg%n"
  level:
    - error
    - com.memorynotfound=trace

等效的application.properties文件:

spring.cache.cache-names: instruments, directory
spring.cache.caffeine.spec: maximumSize=500, expireAfterAccess=30s

logging.pattern.console=%-5level - %msg%n
logging.level.com.memorynotfound=trace
logging.level.=error

测试Caffeine缓存

为了演示我们的方法是否使用缓存,我们编写了一个简单的应用程序。play方法执行多次。

package com.memorynotfound.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class Application implements CommandLineRunner {

    private static Logger log = LoggerFactory.getLogger(Application.class);

    @Autowired
    private MusicService musicService;

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

    @Override
    public void run(String... args) throws Exception {
        log.info("Spring Boot Caffeine Caching Example Configuration");

        play("trombone");
        play("guitar");
        play("trombone");
        play("bass");
        play("trombone");
    }

    private void play(String instrument){
        log.info("Calling: " + MusicServiceIml.class.getSimpleName() + ".play(\"" + instrument + "\");");
        musicService.play(instrument);
    }
}

控制台输出

上一个应用程序将以下输出打印到控制台。我们可以清楚地看到,MusicServiceIml.play("trombone");已缓存。


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

INFO  - Spring Boot Caffeine Caching Example Configuration
INFO  - Calling: MusicServiceIml.play("trombone");
INFO  - Executing: MusicServiceIml.play("trombone");
INFO  - Calling: MusicServiceIml.play("guitar");
INFO  - Executing: MusicServiceIml.play("guitar");
INFO  - Calling: MusicServiceIml.play("trombone");
INFO  - Calling: MusicServiceIml.play("bass");
INFO  - Executing: MusicServiceIml.play("bass");
INFO  - Calling: MusicServiceIml.play("trombone");
 

除特别注明外,本站所有文章均为老K的Java博客原创,转载请注明出处来自https://javakk.com/2180.html

关于

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册