SpringBoot2.7.X集成Ehcache3缓存,编码配置和XML配置

前言

在我这篇文章中SpringBoot2.7.X整合SpringSecurity+JWT、入门级简单易懂 使用的是 spring 自带的缓存,现在使用第三方缓存Ehcache3;这里的重点是编码配置,因为编码配置有两种,springboot 自带的JCacheManagerCustomizer进行集成,另一种是直接使用org.ehcache.CacheManage进行配置

如何选择第三方缓存库?

使用最多的就是 Ehcache 和Redis 这两个缓存库,那如何选择?根据自己的需求。
1、如果需要在多个应用程序之间共享缓存数据,则可以选择 Redis;支持分布式和持久化。
2、如果只需要在单个应用程序中使用本地缓存,则可以选择 Ehcache;支持内存和磁盘存储。

一、介绍 Ehcache3

Ehcache2 和 Ehcache3 是不同的。
在Ehcache3的官网也有介绍:Ehcache3它实现了 JCache 定义的所有 API,并提供了额外的特性和功能;JCache(JSR-107)是 Java 缓存 API 的标准规范。
说白了Ehcache3就是在 JCache上进行了扩展。封装自己的方法、特性、和独有的功能。
你可以使用 JCache 的标准 API 来操作 Ehcache 3,也可以使用 Ehcache 3 特有的 API 来访问其额外的特性和功能。

二、使用Ehcache3

1.引入依赖

因为我上面也介绍了 Ehcache3和 JCache关系,所以JCache必须引用

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!-- Ehcache缓存 -->
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.10.8</version>
        </dependency>
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
        </dependency>

2.编码配置

编码配置有两种第一种是使用springboot 自带的JCacheManagerCustomizer进行集成,另一种是直接使用org.ehcache.CacheManage进行配置

JCacheManagerCustomizer集成

使用spring boot提供的JCacheManagerCustomizer进行集成,是可以使用自带的缓存注解和API的
1、配置application.properties
看到没有 ehcache3 选择的缓存类型不在是ehcache 而是 jcache!!

#ehcache3缓存
spring.cache.type=jcache

2、配置类
注意使用JCacheManagerCustomizer是没办法选择磁盘储存的因为没办法设置磁盘路径,这个问题我搞了很久,就是不行,有大佬知道可以告诉我

@Configuration //配置类
@EnableCaching //开启缓存
public class CacheConfig {
 @Bean
    public JCacheManagerCustomizer jCacheManagerCustomizer() {
        return cm -> {
            //缓存名称,用于登录token的管理
            cm.createCache("userTokenCache", Eh107Configuration.fromEhcacheCacheConfiguration(
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, userTokenCacheInfo.class,
                            ResourcePoolsBuilder.newResourcePoolsBuilder()
                                    .heap(100, EntryUnit.ENTRIES)  // 堆缓存大小为 100 个条目
                                    .offheap(10, MemoryUnit.MB) // 堆外缓存大小为 10 MB
                    )
                            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10))) // 设置缓存的生存时间为 10 秒
                            .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(5))) // 设置缓存的空闲时间为 5 秒
                            .build()));
            //其他的缓存就用这个
            cm.createCache("otherCache", Eh107Configuration.fromEhcacheCacheConfiguration(
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, userTokenCacheInfo.class,
                            ResourcePoolsBuilder.newResourcePoolsBuilder()
                                    .heap(100, EntryUnit.ENTRIES)  // 堆缓存大小为 100 个条目
                                    .offheap(10, MemoryUnit.MB) // 堆外缓存大小为 10 MB
                    )
                            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10))) // 设置缓存的生存时间为 10 秒
                            .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(5))) // 设置缓存的空闲时间为 5 秒
                            .build()));
        };
    }
}
org.ehcache.CacheManage配置

使用ehcache自己的API配置是不需要配置application.properties!
使用ehcache自己的API配置 不能使用springboot自带的缓存注解和API的

import com.stc.login.model.userTokenCacheInfo;

import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.ResourcePools;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder;


@Configuration //配置类
@EnableCaching //开启缓存
public class CacheConfig {

    @Bean
    public CacheManager ehCacheManager() {
        //userTokenCache配置
        CacheConfiguration userTokenCache_cacheConfiguration = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(String.class, userTokenCacheInfo.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                        .heap(100, EntryUnit.ENTRIES) // 堆缓存大小为 100 个条目
                        .offheap(10, MemoryUnit.MB) // 堆外缓存大小为 10 MB
                )
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10))) // 设置缓存的生存时间为 10 秒
                .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(5))) // 设置缓存的空闲时间为 5 秒
                .build();

        //otherCache配置
        CacheConfiguration otherCache_cacheConfiguration = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(String.class, userTokenCacheInfo.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                        .heap(100, EntryUnit.ENTRIES) // 堆缓存大小为 100 个条目
                        .offheap(10, MemoryUnit.MB) // 堆外缓存大小为 10 MB
                        .disk(100, MemoryUnit.MB,true) //磁盘储存,永久储存
                )
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10))) // 设置缓存的生存时间为 10 秒
                .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(5))) // 设置缓存的空闲时间为 5 秒
                .build();


        //7\. 构建
        return newCacheManagerBuilder()
                .with(CacheManagerBuilder.persistence("D:/ehcacheData"))//磁盘储存路径
                .withCache("userTokenCache", userTokenCache_cacheConfiguration)
                .withCache("otherCache",otherCache_cacheConfiguration)
                .build(true);
    }

在其他的地方使用

import org.ehcache.Cache;
import org.ehcache.CacheManager;
 // 获取"userTokenCache"的缓存对象
  Cache <String,String>  cache  = cacheManager.getCache("userTokenCache",String.class,String.class);
//添加一个
 cache.put("test","测试一下")   
//获取
cache.get("test");//测试一下

3、XML配置

xml配置就简单多了网上全是xml配置
看到没有 ehcache3 选择的缓存类型不在是ehcache 而是 jcache!!
只有xml配置所有要把xml配置文件的路径设置好,直接把ehcache.xml跟application放在同一个目录下就好了

1、配置application.properties

#ehcache3缓存
spring.cache.type=jcache
spring.cache.jcache.config=classpath:ehcache.xml

2、ehcache.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.ehcache.org/v3"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
        xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
  <!--磁盘储存路径-->
    <persistence directory="D:/ehcacheData"/> 
    <!--用于用户登录token的管理-->
    <cache alias="userTokenCache">
        <key-type>java.lang.String</key-type>
        <value-type>com.stc.login.model.userTokenCacheInfo</value-type>
        <!-- 省略 <expiry> 标签 就不过期了 -->
        <expiry>
            <!--缓存的生存时间(TTL)为28800-->
            <ttl unit="seconds">28800</ttl>
            <!--缓存的空闲时间(TTI)为20秒 无法同时配置条目的生存时间(TTL)和空闲时间(TTI)-->
            <!--<tti unit="seconds"> 20</tti>-->
        </expiry>
        <resources>
            <!--堆外内存的大小限制为1024MB。-->
            <offheap unit="MB">200</offheap>
        </resources>
    </cache>
    <!--用于otherCache的管理-->
    <cache alias="otherCache">
        <key-type>java.lang.String</key-type>
        <value-type>com.stc.login.model.userTokenCacheInfo</value-type>
        <!-- 省略 <expiry> 标签 就不过期了 -->
        <expiry>
            <!--缓存的生存时间(TTL)为30-->
            <ttl unit="seconds">30</ttl>
            <!--缓存的空闲时间(TTI)为20秒 无法同时配置条目的生存时间(TTL)和空闲时间(TTI)-->
            <!--<tti unit="seconds"> 20</tti>-->
        </expiry>
        <resources>
            <!--堆内存的大小限制为2个条目-->
            <heap unit="entries">2</heap>
            <!--堆外内存的大小限制为10MB。-->
            <offheap unit="MB">10</offheap>
            <!--磁盘缓存 persistent属性用于指定磁盘缓存是否持久化-->
            <disk unit="MB" persistent="false">20</disk>
        </resources>
    </cache>
</config>

3、给启动类上加上@EnableCaching
给启动类上加上@EnableCaching开启缓存,

@EnableCaching //开启缓存
public class StcEasApplication {
    public static void main(String[] args) {
        SpringApplication.run(StcEasApplication.class, args);
    }
}

这样就可以使用了。可以使用自带的缓存注解和API了
缓存注解怎么使用网上也是很多,API使用就少了,API怎么使用可以去看看我的SpringBoot2.7.X整合SpringSecurity+JWT、入门级简单易懂这篇的UserTokenCacheServiceImpl 这个类的代码

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
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缓存可以有效地提高应用程序的性能和响应速度。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值