EehCache介绍、应用场景和示例代码

18 篇文章 0 订阅
5 篇文章 0 订阅

EhCache 概述

EhCache 是一个高性能、轻量级的 Java 缓存库,广泛应用于各种 Java 应用中。EhCache 提供了丰富的功能,包括内存缓存、磁盘缓存、分布式缓存、持久化等,并且可以和 Spring 框架无缝集成。它支持基于内存和磁盘的混合存储,允许缓存数据在内存满时自动溢出到磁盘。

EhCache 的特点

  • 易于集成:EhCache 易于与 Spring 等框架集成,并提供了直观的配置方式。
  • 高性能:支持多种缓存策略(如 LRU、LFU、FIFO),以优化性能。
  • 可扩展性:支持分布式缓存,可以与 Terracotta 集成实现集群缓存。
  • 灵活性:支持多种存储机制,用户可以根据需求选择在内存、磁盘或两者混合存储缓存数据。

应用场景

  1. 数据层缓存:通过缓存数据库查询结果来减少数据库访问频率,提升应用的响应速度。

  2. Web 应用缓存:缓存网页或部分页面的生成结果,以减少服务器负载。

  3. 计算结果缓存:在计算密集型应用中缓存结果,避免重复计算。

  4. 配置缓存:缓存配置数据,避免频繁访问配置文件或外部配置服务。

示例代码

以下是一个使用 EhCache 进行缓存的简单示例。

1. 引入依赖

pom.xml 中添加 EhCache 和 Spring Cache 的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 配置 EhCache

创建 ehcache.xml 配置文件,放在 src/main/resources 目录下:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="false"
         monitoring="autodetect"
         dynamicConfig="true">

    <cache name="books"
           maxEntriesLocalHeap="1000"
           maxEntriesLocalDisk="10000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>
3. 配置 Spring Cache 使用 EhCache

创建 Spring 的缓存配置类:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public EhCacheCacheManager cacheManager() {
        net.sf.ehcache.CacheManager ehCacheManager = net.sf.ehcache.CacheManager.newInstance(
                new ClassPathResource("ehcache.xml").getInputStream());
        return new EhCacheCacheManager(ehCacheManager);
    }
}
4. 使用缓存注解

在服务层使用 @Cacheable 注解来缓存方法的返回值:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class BookService {

    @Cacheable("books")
    public Book findBookByIsbn(String isbn) {
        // 模拟耗时操作,如数据库查询
        simulateSlowService();
        return new Book(isbn, "Some Book Title");
    }

    private void simulateSlowService() {
        try {
            Thread.sleep(3000L); // 模拟慢速服务
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}
5. 测试缓存

通过调用服务层方法来测试缓存功能:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements CommandLineRunner {

    @Autowired
    private BookService bookService;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Fetching book...");
        System.out.println(bookService.findBookByIsbn("isbn-1234"));
        System.out.println("Fetching book again...");
        System.out.println(bookService.findBookByIsbn("isbn-1234"));
    }
}
6. 运行结果

第一次调用 findBookByIsbn("isbn-1234") 时,方法会执行并返回结果,同时结果会被缓存。第二次调用时,将直接从缓存中获取数据,不再执行耗时操作。

代码解释

  1. EhCache 配置

    • maxEntriesLocalHeap:设置缓存的最大堆内存条目数。
    • maxEntriesLocalDisk:设置缓存的最大磁盘存储条目数。
    • timeToIdleSecondstimeToLiveSeconds:分别指定缓存条目在闲置和存活时长之后过期。
    • memoryStoreEvictionPolicy:设置内存存储的逐出策略,如 LRU(最近最少使用)。
  2. @EnableCaching:开启 Spring 的缓存支持。

  3. EhCacheCacheManager:将 EhCache 与 Spring Cache 集成。

  4. @Cacheable 注解:标记的方法返回值会被缓存,缓存的 key 是方法参数(如 isbn)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值