V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hansonwang99
V2EX  ›  程序员

Springboot 应用缓存实践之: Ehcache 加持

  •  
  •   hansonwang99 ·
    hansonwang99 · 2018-10-10 21:01:19 +08:00 · 2201 次点击
    这是一个创建于 1996 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Profile

    注: 本文首发于 博客 CodeSheep · 程序羊,欢迎光临 小站


    概述

    在如今高并发的互联网应用中,缓存的地位举足轻重,对提升程序性能帮助不小。而 3.x 开始的 Spring 也引入了对 Cache 的支持,那对于如今发展得如火如荼的 Spring Boot 来说自然也是支持缓存特性的。当然 Spring Boot 默认使用的是 SimpleCacheConfiguration,即使用 ConcurrentMapCacheManager 来实现的缓存。但本文将讲述如何将 Ehcache 缓存应用到 Spring Boot 应用中。

    「 Ehcache 」 是一个基于 Java 实现的开源缓存管理库,提供了用内存、磁盘文件存储、以及分布式存储等多种灵活的管理方案。使用方式和原理都有点类似于 Spring 事务管理,配合各项注解可以很容易的上手。

    下文就上手来摸一摸它,结合对数据库的操作,我们让 Ehcache 作为本地缓存来看一下效果!


    准备工作

    • 准备好数据库和数据表并插入相应的数据( MySQL )

    比如我这里准备了一张用户表,包含几条记录:

    准备好 MySQL 数据库和数据表

    我们将通过模拟数据库的存取操作来看看 Ehcache 缓存加入后的效果。


    搭建工程:Springboot + MyBatis + MySQL + Ehcache

    pom.xml 中添加如下依赖:

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!--for mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
    
            <!--for Mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
            <!-- Spring boot Cache-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>
    
            <!--for ehcache-->
            <dependency>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache</artifactId>
            </dependency>
    
        </dependencies>
    

    建立 Ehcache 配置文件

    创建 Ehcache 的配置文件 ehcache.xml 并置于项目 classpath 下:

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache>
    
        <diskStore path="java.io.tmpdir"/>
    
        <!-- 设定缓存的默认数据过期策略 -->
        <defaultCache
                maxElementsInMemory="10000"
                eternal="false"
                timeToIdleSeconds="120"
                timeToLiveSeconds="120"
                overflowToDisk="true"
                maxElementsOnDisk="10000000"
                diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120"
                memoryStoreEvictionPolicy="LRU"/>
    
        <cache name="user"
               maxElementsInMemory="1000"
               eternal="false"
               timeToIdleSeconds="10"/>
    
    </ehcache>
    

    配置 application.properties

    server.port=80
    
    # Mysql 数据源配置
    spring.datasource.url=jdbc:mysql://121.196.213.251:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=xxxxxx
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    # mybatis 配置
    mybatis.type-aliases-package=cn.codesheep.springbt_ehcache.entity
    mybatis.mapper-locations=classpath:mapper/*.xml
    mybatis.configuration.map-underscore-to-camel-case=true
    
    # ehcache 配置
    spring.cache.ehcache.config=classpath:ehcache.xml
    

    编写操作数据库和 Ehcache 缓存的业务代码

    • 编写 entity
    public class User {
    
        private Long userId;
        private String userName;
        private Integer userAge;
    
        public Long getUserId() {
            return userId;
        }
    
        public void setUserId(Long userId) {
            this.userId = userId;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public Integer getUserAge() {
            return userAge;
        }
    
        public void setUserAge(Integer userAge) {
            this.userAge = userAge;
        }
    }
    
    • 编写 mapper
    public interface UserMapper {
    
        List<User> getUsers();
    
        int addUser(User user);
    
        List<User> getUsersByName( String userName );
    }
    
    • 编写 service
    @Service
    public class UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        public List<User> getUsers() {
            return userMapper.getUsers();
        }
    
        public int addUser( User user ) {
            return userMapper.addUser(user);
        }
    
        @Cacheable(value = "user", key = "#userName")
        public List<User> getUsersByName( String userName ) {
            List<User> users = userMapper.getUsersByName( userName );
            System.out.println( "从数据库读取,而非读取缓存!" );
            return users;
        }
    }
    

    看得很明白了,我们在 getUsersByName接口上添加了注解:@Cacheable。这是 Ehcache 的使用注解之一,除此之外常用的还有 @CachePut@CacheEvit,分别简单介绍一下:

    1. @Cacheable:配置在 getUsersByName方法上表示其返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问
    2. @CachePut:配置于方法上时,能够根据参数定义条件来进行缓存,其与 @Cacheable不同的是使用 @CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中,所以主要用于数据新增和修改操作上
    3. @CacheEvict:配置于方法上时,表示从缓存中移除相应数据。
    • 编写 controller
    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @Autowired
        CacheManager cacheManager;
    
        @GetMapping("/users")
        public List<User> getUsers() {
            return userService.getUsers();
        }
    
        @GetMapping("/adduser")
        public int addSser() {
            User user = new User();
            user.setUserId(4l);
            user.setUserName("赵四");
            user.setUserAge(38);
            return userService.addUser(user);
        }
    
        @RequestMapping( value = "/getusersbyname", method = RequestMethod.POST)
        public List<User> geUsersByName( @RequestBody User user ) {
            System.out.println( "-------------------------------------------" );
            System.out.println("call /getusersbyname");
            System.out.println(cacheManager.toString());
            List<User> users = userService.getUsersByName( user.getUserName() );
            return users;
        }
    
    }
    

    改造 SpringBoot 应用主类

    主要是在启动类上通过 @EnableCaching 注解来显式地开启 Ehcache 缓存

    @SpringBootApplication
    @MapperScan("cn.codesheep.springbt_ehcache")
    @EnableCaching
    public class SpringbtEhcacheApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbtEhcacheApplication.class, args);
        }
    }
    

    最终完工的整个工程的结构如下:

    完整工程结构


    实际实验

    通过多次向接口 localhost/getusersbynamePOST 数据来观察效果:

    向接口提交数据

    可以看到缓存的启用和失效时的效果(上文 ehcache 的配置文件中设置了缓存 user 的实效时间为 10s ):

    缓存的启用和失效时的数据取数据效果


    后 记

    由于能力有限,若有错误或者不当之处,还请大家批评指正,一起学习交流!

    本文实验代码在此



    第 1 条附言  ·  2018-10-10 21:51:32 +08:00
    5 条回复    2018-10-11 09:39:50 +08:00
    qiyuey
        1
    qiyuey  
       2018-10-10 21:56:34 +08:00
    内容略基础
    wm5d8b
        2
    wm5d8b  
       2018-10-10 22:18:55 +08:00 via Android
    内容略过时,spring cache 这种接口了解一下
    letitbesqzr
        3
    letitbesqzr  
       2018-10-11 00:00:19 +08:00   ❤️ 1
    我感觉 Ehcache 已经慢慢没优势了,复杂 /量大 的缓存上 redis , 如果是很简单的缓存到内存下,选择用 ConcurrentReferenceHashMap 也是挺不错的,或者还要带点什么过期机制啥的,选择 guava cache 或者 caffeine 感觉都比 Ehcache 优秀。
    abcbuzhiming
        4
    abcbuzhiming  
       2018-10-11 09:28:08 +08:00
    @letitbesqzr caffeine 本来就是 guava cache 的续任者,更是直接被 spring5 选用的默认缓存,ehcache 存在一些问题,caffeine 在 git 上的 wiki 指名道姓的指责 ehcache 的开发者以“自以为是”的态度开发他们的软件,以“空想理论”的方式,宣称他们的缓存的性能。敢这么说,我估计 ehcache 真恐怕有不少问题。现在看 ehcache 除了能做独立集群,真心没有比别家缓存强到哪里,但是如果我要做独立集群缓存,我为啥不选 redis,memcache 呢。
    337136897
        5
    337136897  
       2018-10-11 09:39:50 +08:00
    @abcbuzhiming 有道理,给你 100 个赞
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5362 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 08:00 · PVG 16:00 · LAX 01:00 · JFK 04:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.