微人事第九天:spring cache整合Ehcache

用惯了 Redis ,很多人已经忘记了还有另一个缓存方案 Ehcache ,是的,在 Redis 一统江湖的时代,Ehcache 渐渐有点没落了,不过,我们还是有必要了解下 Ehcache ,在有的场景下,我们还是会用到 Ehcache。
Spring Cache 可以整合 Redis,当然也可以整合 Ehcache,两种缓存方案的整合还是比较相似,主要是配置的差异,具体的用法是一模一样的,就类似于 JDBC 和 数据库驱动的关系一样。前面配置完成后,后面具体使用的 API 都是一样的。

和 Spring Cache + Redis 相比,Spring Cache + Ehcache 主要是配置有所差异,具体的用法是一模一样的。我们来看下使用步骤。
1.创建springboot项目
加入web和cache依赖,Ehcache依赖需要手动添加。
在这里插入图片描述
在pom.xml中添加Ehcache依赖

<dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.6</version>
        </dependency>

2.添加ehcache.xml配置

<ehcache>
    <diskStore path="java.io.tmpdir/ehcache"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
    />
    <cache name="mycache"
           timeToIdleSeconds="120"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="true"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="600"/>
</ehcache>

配置含义:

1.name:缓存名称。
2.maxElementsInMemory:缓存最大个数。
3.eternal:对象是否永久有效,一但设置了,timeout将不起作用。
4.timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。
5.仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
6.timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
7.overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
8.diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
9.maxElementsOnDisk:硬盘最大缓存个数。
10.diskPersistent:是否缓存虚拟机重启期数据。
11.diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
12.memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
13.clearOnFlush:内存数量最大时是否清除。
14.diskStore 则表示临时缓存的硬盘目录。

如果xml文件不以ehcache为名,则还需要再application.properties中配置名称

3.cache相关操作
以下操作和cache中的一样
实体类user需要序列化

package org.javaboy.ehcache;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;
    private String name;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

service类,注解就是cache中使用的注解

package org.javaboy.ehcache;

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

@Service
public class UserService {

    @Cacheable(cacheNames = "mycache")
    public User getUserById(Integer id) {
        User user = new User();
        user.setId(id);
        System.out.println("getUserById>>>" + id);
        return user;
    }
}

启动类也同样

package org.javaboy.ehcache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class EhcacheApplication {

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

}

4.测试类
在测试方法中调用同样的方法,并且参数也要相同,查看是否ehcache配置生效。

package org.javaboy.ehcache;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EhcacheApplicationTests {

    @Autowired
    private UserService userService;

    @Test
    public void contextLoads() {
        User u1 = userService.getUserById(1);
        User u2 = userService.getUserById(1);
        System.out.println(u1);
        System.out.println(u2);
    }

}

运行之后结果,可以看出ehcache配置生效了,第二次调用同样的方法,没有再次执行而是去ehcache中获取。

getUserById>>>1
User{id=1, name='null', address='null'}
User{id=1, name='null', address='null'}

总结:
spring cahce整合Ehcache和整合redis的java代码都是一样的,唯一的不同就是配置不同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值