首页 > 技术文章 > SpringBoot 整合 EhCache

Bin-x 2021-12-17 23:54 原文

目前SpringBoot提供的 spring-boot-starter-cache 默认支持EhCache 2.x

1. 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.9.2</version>
</dependency>

2. 添加配置文件

新建文件 src/main/resources/ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://www.ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--diskStore 磁盘存储位置-->
    <diskStore path="java.io.tmpdir/ehcache"/>
    <!--这个默认缓存在SpringBoot中不生效,但是必须配置-->
    <defaultCache/>
    <!--
    name:缓存名称,及注解中value的值
    maxEntriesLocalHeap:堆内存中最大缓存对象数
    eternal:是否永久缓存
    timeToIdleSeconds:缓存的过期访问间隔,超过此间隔没有访问该缓存会过期
    timeToLiveSeconds:缓存的最大存活时间
    -->
    <cache  name="custom"
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

 

3. 修改启动类

在启动类上添加 @EnableCaching 注解

package com.example.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. 使用

  • 新建实体类
package com.example.ehcache.dao;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = -7596076576088137093L;
    private int id;
    private String name;
    private int age;
}
  • 接口
package com.example.ehcache.services;

import com.example.ehcache.dao.User;

public interface IUserService {
    public User findUserById(int id);
    public User findUser(int id);
    public void deleteUser(int id);
    public void deleteAll();
}
  •  服务
package com.example.ehcache.services.impl;

import com.example.ehcache.dao.User;
import com.example.ehcache.services.IUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService implements IUserService {
    @Override
    @Cacheable(value = "custom", key = "'user:'+#id")
    public User findUserById(int id) {
        System.out.println("get user " + id);
        return new User(id, "User" + id, 18);
    }

    @Override
    @CachePut(value = "custom",key = "'user:'+#id")
    public User findUser(int id) {
        System.out.println("get user " + id);
        return new User(id, "User" + id, 19);
    }

    @Override
    @CacheEvict(value = "custom",key = "'user:'+#id")
    public void deleteUser(int id) {

    }

    @Override
    @CacheEvict(value = "custom",allEntries = true)
    public void deleteAll() {

    }
}
  • 测试
package com.example.ehcache;

import com.example.ehcache.dao.User;
import com.example.ehcache.services.IUserService;
import net.sf.ehcache.CacheManager;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;

@SpringBootTest
class EhcacheApplicationTests {

    @Autowired
    private IUserService userService;

    @Test
    void contextLoads() {
        //第一次获取user1
        User user1 = userService.findUserById(1);
        System.out.println(user1);
        //第一次获取user2
        User user2 = userService.findUserById(2);
        System.out.println(user2);

        System.out.println("------------第一次获取user----------------");

        //从缓存中获取user1
        user1 = userService.findUserById(1);
        System.out.println(user1);

        System.out.println("--------------从缓存中获取user1--------------");

        //更新user1
        user1 = userService.findUser(1);
        System.out.println(user1);

        System.out.println("--------------更新user1--------------");

        //从缓存中删除user2
        userService.deleteUser(2);
        user2 = userService.findUserById(2);
        System.out.println(user2);

        System.out.println("--------------从缓存中删除user2--------------");

        //从缓存中删除所有user
        userService.deleteAll();
        //重新获取user1
        user1 = userService.findUserById(1);
        System.out.println(user1);
        //重新获取user2
        user2 = userService.findUserById(2);
        System.out.println(user2);
        System.out.println("--------------从缓存中删除所有user--------------");
    }

}

推荐阅读