Spring boot基于Ehcache的内存缓存策略实现

3 篇文章 0 订阅
1 篇文章 0 订阅

一、Ehcache缓存简介

1、Ehcache基础介绍

EhCache 是一个纯Java的进程内缓存框架,具有快速熟悉、上手简单等特点,是Hibernate框架默认的缓存提供方。

2、Hibernate缓存机制简介

hibernate提供了两级缓存,分别为一级session级缓存策略,二级是SessionFactory对象缓存。在此基础上可以配置三层查询缓存也就是整合此次介绍的Ehcache。

一级缓存:基于session级别的分配的一块内存空间,一般情况下session对象的生命周期对应的是一数据库事物或应用事物,因此它的缓存是事务范围的缓存,是一个必须的缓存。

二级缓存:SessionFactory对象缓存,可以被创建出的多个 Session 对象共享,SessionFactory对象的生命周期和应用程序的整个过程对应,因此第二级缓存是进程范围或者集群范围的缓存。这个缓存中存放的对象的松散数据。二级缓存默认是关闭的,如果要使用需要手动开启,并且依赖EhCache组件。

三级缓存:查询缓存,配置开启该缓存的情况下,重复使用一个sql查询某个范围内的数据,会进行缓存。

3、EhCache缓存特点

  • 快速,简单,并且提供多种缓存策略;
  • 缓存数据有两级:内存和磁盘,无需担心容量问题;
  • 缓存数据会在虚拟机重启的过程中写入磁盘;
  • 可以通过RMI、可插入API等方式进行分布式缓存;
  • 具有缓存和缓存管理器的侦听接口;
  • 支持多缓存管理器实例,以及一个实例的多个缓存区域;
  • 提供Hibernate的缓存实现;

4、对比redis缓存策略

Ehcache:直接在Jvm虚拟机中缓存,速度快,效率高,不适合处理大规模缓存数据,在分布式环境下,缓存数据共享操作复杂;

Redis:作为独立的缓存中间件,在分布式缓存系统中非常好用,缓存数据共享,有效支撑大量数据缓存,支持哨兵模式,或者集群模式的高可用成熟方案;

二、SpringBoot框架中集成EhCache

1、核心依赖引入

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

2、加载配置文件

spring:
  cache:
    ehcache:
      config: classpath:ehcache.xml

3、配置文件的详情

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <!-- 操作系统缓存的临时目录,内存满后写入该目录 -->
    <diskStore path="java.io.tmpdir"/>

    <defaultCache
            maxElementsInMemory="1000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="UserInfo"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

配置参数说明

maxElementsOnDisk:磁盘缓存中最多可以存放的元素数量;

eternal:缓存中对象是否永久有效;

timeToIdleSeconds:当eternal=false时使用,缓存数据有效期(单位:秒),时间段内没有访问该元素,将被清除;

timeToLiveSeconds:缓存数据的存活时间;

maxElementsInMemory:内存中最多可以存放的元素数量,overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中,若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素;

diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔;

memoryStoreEvictionPolicy:缓存释放策略,LRU会优先清理最少使用的缓存;

localTempSwap:持久化策略,当堆内存或者非堆内存里面的元素已经满了的时候,将其中的元素临时的存放在磁盘上,重启后就会消失;

4、启动类的注解配置

@EnableCaching
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class,args) ;
    }
}

三、项目中EhCache 注解用法

@Service
public class CacheService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CacheService.class);

    @Resource
    private UserMapper userMapper ;

    @Cacheable(value="UserInfo")  // 在缓存有效期内,首次查询才访问数据库
    public UserEntity getById (String id){
        // 通过日志,标识方法是否执行
        LOGGER.info("getById..."+id);
        return userMapper.selectById(id) ;
    }

    @CacheEvict(value="UserInfo",key = "#id") //该ID数据更新,清空该ID缓存
    public void updateUser(String id) {
        UserInfo user = new UserInfo () ;
        user.setId(id);
        user.setUserName("myCache");
        userMapper.updateById(user);
    }
}

注解参数说明

@Cacheable:注解标记在一个方法上,也可以标记在一个类上,标记在一个方法上表示该方法支持缓存,该方法被调用后将其返回值缓存起来,下次同样的请求参数执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。

@CacheEvict:注解标记在需要清除缓存元素的方法或类上的,当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作,并且可以按照指定属性清除。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 添加 Ehcache 依赖 在 Maven 中添加 Ehcache 的依赖: ```xml <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.8.1</version> </dependency> ``` 2. 创建 Ehcache 配置文件 在项目的 classpath 下创建 Ehcache 的配置文件 ehcache.xml,配置缓存策略缓存区域。 示例: ```xml <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd"> <cache alias="userCache"> <key-type>java.lang.String</key-type> <value-type>com.example.User</value-type> <expiry> <ttl unit="seconds">60</ttl> <tti unit="seconds">30</tti> </expiry> <resources> <heap unit="entries">100</heap> <offheap unit="MB">10</offheap> </resources> </cache> </config> ``` 3. 配置 Ehcache 缓存管理器 在 Spring Boot 中,可以通过注解 @EnableCaching 和 @Configuration 注解来配置 Ehcache 缓存管理器。 示例: ```java @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager() { Resource resource = new ClassPathResource("ehcache.xml"); Configuration configuration = ConfigurationFactory.parseConfiguration(resource.getInputStream()); return CacheManagerBuilder.newCacheManagerBuilder() .withCache("userCache", UserCacheConfigurationBuilder.newUserCacheConfigurationBuilder().buildConfig(String.class, User.class)) .withCache("bookCache", BookCacheConfigurationBuilder.newBookCacheConfigurationBuilder().buildConfig(Long.class, Book.class)) .withConfiguration(configuration) .build(true); } } ``` 4. 使用 Ehcache 缓存管理器 在需要使用缓存的方法上添加 @Cacheable、@CachePut 或 @CacheEvict 注解来实现缓存的读取、写入和删除。 示例: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "userCache", key = "#id") public User getUserById(String id) { return userRepository.findById(id).orElse(null); } @CachePut(value = "userCache", key = "#user.id") public User saveOrUpdateUser(User user) { return userRepository.save(user); } @CacheEvict(value = "userCache", key = "#id") public void deleteUserById(String id) { userRepository.deleteById(id); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值