Springboot整合ehcache缓存

释放双眼,带上耳机,听听看~!

EhCache是一个比较成熟的Java缓存框架,最早从hibernate发展而来, 是进程中的缓存系统,它提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案,快速简单。

Springboot对ehcache的使用非常支持,所以在Springboot中只需做些配置就可使用,且使用方式也简易。

在你的项目上配置以下几步即可使用

首先,老规矩,pom.xml加依赖;


1
2
3
4
5
6
7
8
9
10
11
1<!-- Spring Boot 缓存支持启动器 -->
2       <dependency>
3           <groupId>org.springframework.boot</groupId>
4           <artifactId>spring-boot-starter-cache</artifactId>
5       </dependency>
6       <!-- Ehcache 坐标 -->
7       <dependency>
8           <groupId>net.sf.ehcache</groupId>
9           <artifactId>ehcache</artifactId>
10      </dependency>
11

第二步,创建ehcache.xml配置文件

位置:classpath目录下,即src/main/resources/ehcache.xml

文件内容开发的时候可参考第一步导入的jar包,具体在哪呢,看下面:

Springboot整合ehcache缓存Springboot整合ehcache缓存

再看代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
1<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
2
3    <diskStore path="java.io.tmpdir"/>
4
5  <!--defaultCache:echcache的默认缓存策略  -->
6    <defaultCache
7            maxElementsInMemory="10000"
8            eternal="false"
9            timeToIdleSeconds="120"
10            timeToLiveSeconds="120"
11            maxElementsOnDisk="10000000"
12            diskExpiryThreadIntervalSeconds="120"
13            memoryStoreEvictionPolicy="LRU">
14        <persistence strategy="localTempSwap"/>
15    </defaultCache>
16    <cache name="users"
17            maxElementsInMemory="10000"
18            eternal="false"
19            timeToIdleSeconds="120"
20            timeToLiveSeconds="120"
21            maxElementsOnDisk="10000000"
22            diskExpiryThreadIntervalSeconds="120"
23            memoryStoreEvictionPolicy="LRU">
24        <persistence strategy="localTempSwap"/>
25    </cache>
26</ehcache>
27

说明:


1
2
1<diskStore path="java.io.tmpdir"/>这个是磁盘存储路径,当内存缓存满了的时候,就会往这里面放,java.io.tmdir是操作系统缓存的临时目录,不同操作系统缓存目录不一样。
2

1
2
3
4
1maxElementsInMemory      内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况  
2                         1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中  
3                         2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素
4

1
2
1overflowToDisk           内存不足时,是否启用磁盘缓存
2

1
2
1eternal                  缓存中对象是否永久有效
2

1
2
1timeToIdleSeconds        缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
2

1
2
1timeToLiveSeconds        缓存数据的总的存活时间(单位:秒),仅当eternal=false时使用,从创建开始计时,失效结束。
2

1
2
1maxElementsOnDisk        磁盘缓存中最多可以存放的元素数量,0表示无穷大
2

1
2
1diskExpiryThreadIntervalSeconds   磁盘缓存的清理线程运行间隔,默认是120秒
2

1
2
3
4
1memoryStoreEvictionPolicy   内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存  共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)  
2另外,defaultCache是默认缓存方式,cache是自定义的缓存方式,自行设置name  
3第三步,在Springboot配置文件中把ehcache.xml配置进去;即在application.properties中加入以下配置代码
4

1
2
1spring.cache.ehcache.config=ehcache.xml
2

第三步结束,ehcache在Springboot中就配置完成了,下面就是怎么在Springboot中使用

第四步,在启动类前加上@EnableCaching注解;这样的话,启动类启动时会去启动缓存启动器。


1
2
3
4
5
6
7
8
9
10
11
12
1@SpringBootApplication
2@MapperScan("com.yunxing.mapper")
3@EnableCaching
4public class app {
5
6   public static void main(String[] args) {
7       SpringApplication.run(app.class, args);
8
9   }
10
11}
12

  第五步,实体类实现可序列化接口Serializable;由于需要实体类支持缓存中的磁盘存储,所以需要实体类实现可序列化接口


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1public class user implements Serializable{
2    private Integer id;
3    private String name;
4    private Integer age;
5   public Integer getId() {
6       return id;
7   }
8   public void setId(Integer id) {
9       this.id = id;
10  }
11  public String getName() {
12      return name;
13  }
14  public void setName(String name) {
15      this.name = name;
16  }
17  public Integer getAge() {
18      return age;
19  }
20  public void setAge(Integer age) {
21      this.age = age;
22  }
23    
24}
25

第六步,使用@Cacheable把数据存进缓存,下面就是专门把方法返回值存入缓存


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1@Service
2@Transactional     //事务,表示该类下所有的都受事务控制
3public class userServiceImpl implements userService {
4   @Autowired
5    private userMapper usermapper;
6   @Override
7   @Cacheable(value="users")
8   public user selectUserById(int id) {
9       user user=this.usermapper.selectUserById(id);
10      System.out.println("1111111111111111111111111");
11      return user;
12  }
13
14}
15

说明: @Cacheable可以标记在一个方法上,也可以标记在一个类上,当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。对于一个支持缓存的方法,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。Spring在缓存方法的返回值时是以键值对进行缓存的,值就是方法的返回结果。

                 @Cacheable可以指定三个属性,value、key和condition。

                                  value属性指定cache的名称(即选择ehcache.xml中哪种缓存方式存储)

                                  key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。我们也直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
1@Cacheable(value="users", key="#id")
2
3   public User find(Integer id) {
4
5      returnnull;
6
7   }
8
9
10
11   @Cacheable(value="users", key="#p0")
12
13   public User find(Integer id) {
14
15      returnnull;
16
17   }
18
19
20
21   @Cacheable(value="users", key="#user.id")
22
23   public User find(User user) {
24
25      returnnull;
26
27   }
28
29
30
31   @Cacheable(value="users", key="#p0.id")
32
33   public User find(User user) {
34
35      returnnull;
36
37   }
38

   最后,使用@CacheEvict清除缓存;


1
2
3
4
5
1@CacheEvict(value="users",allEntries=true)
2public void saveUsers(Users users) {
3this.usersRepository.save(users);
4}
5

说明:@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。

                    其中value、key和condition的语义与@Cacheable对应的属性类似;allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。

                   当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

 

 

 

 


1
2

2

 

 

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

Ubuntu下安装Mysql 以及mysql-query-browser

2022-1-11 12:36:11

气候事件

“威马逊”余威尚存 中东部高温悄然兴起

2014-7-20 10:34:33

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索