在 Spring Boot 应用中集成 Ehcache 并使用多个缓存实例

添加依赖
在 pom.xml 文件中添加 Ehcache 的依赖:

   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-cache</artifactId>
   </dependency>
   <dependency>
       <groupId>net.sf.ehcache</groupId>
       <artifactId>ehcache</artifactId>
   </dependency>
   

注意:spring-boot-starter-cache 是必需的,因为它提供了 Spring Cache 抽象层,而 ehcache 依赖则是实际的缓存实现。
配置 Ehcache
创建或修改 application.yml 或 application.properties 文件来配置 Ehcache。例如,在 application.yml 中添加:

   spring:
     cache:
       cache-names: cache1, cache2
       ehcache:
         config: classpath:ehcache.xml
   

或者在 ehcache.xml 文件中直接定义多个缓存实例:

   <?xml version="1.0" encoding="UTF-8"?>
   <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
     <diskStore path="java.io.tmpdir"/>
     <defaultCache maxElementsInMemory="10000"
                   eternal="false"
                   timeToIdleSeconds="120"
                   timeToLiveSeconds="120"
                   overflowToDisk="false"
                   diskPersistent="false"/>
     
     <!-- 定义第一个缓存实例 -->
     <cache name="cache1"
            maxElementsInMemory="1000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"/>

     <!-- 定义第二个缓存实例 -->
     <cache name="cache2"
            maxElementsInMemory="2000"
            eternal="false"
            timeToIdleSeconds="180"
            timeToLiveSeconds="180"
            overflowToDisk="false"
            diskPersistent="false"/>
   </ehcache>
   

3,使用缓存
在服务层或 DAO 层使用 @Cacheable、@CachePut 和 @CacheEvict 注解来操作缓存。
例如:

   @Service
   public class MyService {

       @Autowired
       private MyRepository myRepository;

       @Cacheable(value = "cache1", key = "#id")
       public MyEntity findById(Long id) {
           return myRepository.findById(id);
       }

       @CachePut(value = "cache1", key = "#myEntity.id")
       public MyEntity update(MyEntity myEntity) {
           return myRepository.save(myEntity);
       }

       @CacheEvict(value = "cache1", key = "#id")
       public void deleteById(Long id) {
           myRepository.deleteById(id);
       }
   }
   

上述示例中,cache1 是在 ehcache.xml 中定义的第一个缓存实例名称。
4,多实例支持
如果需要使用多个缓存实例,可以在注解中指定不同的缓存名称:

   @Cacheable(value = {"cache1", "cache2"}, key = "#id")
   

这样,同一个方法调用将被同时缓存在两个不同的缓存实例中。

5,非注解的方式直接与 Ehcache API 交互

首先,你需要初始化 Ehcache。这通常在应用启动时完成,可以放在一个配置类或者初始化器中。

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;

import java.time.Duration;

public class EhcacheConfig {

    private static CacheManager cacheManager;
    private static Cache<String, String> cache;

    public static void init() {
        // 创建 CacheManager
        cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
        cacheManager.init();

        // 创建 Cache 配置
        CacheConfiguration<String, String> cacheConfig = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(String.class, String.class,
                        ResourcePoolsBuilder.heap(100))
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(5)))
                .build();

        // 创建 Cache
        cache = cacheManager.createCache("myCache", cacheConfig);
    }

    public static Cache<String, String> getCache() {
        return cache;
    }
}

使用 Ehcache

一旦初始化完成,你就可以在任何需要的地方使用 Ehcache 了。下面是如何在服务类中使用缓存的例子:

public class MyService {

    public String getData(String key) {
        Cache<String, String> cache = EhcacheConfig.getCache();

        // 尝试从缓存中获取数据
        String result = cache.get(key);

        if (result == null) {
            // 如果缓存中没有数据,则从数据库或其他地方获取
            result = fetchFromDatabase(key);
            // 将数据放入缓存
            cache.put(key, result);
        }

        return result;
    }

    private String fetchFromDatabase(String key) {
        // 从数据库获取数据的逻辑
        return "data from db for key: " + key;
    }
}

清理和关闭 Ehcache

当应用结束时,记得关闭 CacheManager 来释放资源。

public class ApplicationShutdownHook extends Thread {

    @Override
    public void run() {
        if (EhcacheConfig.cacheManager != null) {
            EhcacheConfig.cacheManager.close();
        }
    }
}

// 在应用启动时注册 shutdown hook
Runtime.getRuntime().addShutdownHook(new ApplicationShutdownHook());

这种方式允许你更细粒度地控制缓存的读取、写入和清理过程,但同时也需要你处理更多的细节,比如并发控制、异常处理等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值