Java Demo示例:springboot下使用ehcache/JSR实现缓存机制

1、EhCache概述

        SpringBoot支持很多种缓存方式:redis、guava、Caffeine、ehcahe、jcache等等,我们这里主要了解ehcahe。

        Ehcache 是一种开源的、基于标准的缓存,可提高性能、卸载数据库并简化可扩展性。它是最广泛使用的基于 Java 的缓存,因为它健壮、经过验证、功能齐全,并且与其他流行的库和框架集成。Ehcache 从进程内缓存扩展到具有 TB 级缓存的混合进程内/进程外部署。

        Ehcache也提供分布式集群,不过就易用性和成熟度相比之下redis可能更适合大型应用做分布式缓存。

        另外它提供了JSR-107缓存管理器的实现。Java Specification Request,简写JSR,JSR是Java Specification Requests的缩写,意思是Java 规范提案。2012年10月26日JSR规范委员会发布了JSR 107(JCache API的首个早期草案。JCache规范定义了一种对Java对象临时在内存中进行缓存的方法,包括对象的创建、共享访问、假脱机(spooling)、失效、各JVM的一致性等,可被用于缓存JSP内最经常读取的数据。

2、缓存配置

        为了开始使用 Ehcache,您需要配置您的第一个CacheManager和Cache. 这可以通过编程配置或XML来实现。

(1)使用 POJO 配置

        我们可以创建一个service进行缓存统一的管理。

package com.home.skydance.service;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class CacheService {

    private CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
    private Cache<Integer, Object> squareNumberCache ;

    public CacheService() {
        this.cacheManager.init();
        this.squareNumberCache = cacheManager
                .createCache("squaredNumber", CacheConfigurationBuilder
                        .newCacheConfigurationBuilder(Integer.class, Object.class, ResourcePoolsBuilder.heap(10)));
    }

    /**
     * 添加数据
     * @param list
     */
    public void addMenuListToCache(List<String> list)
    {
        this.cacheManager.getCache("squaredNumber", Integer.class, Object.class).put(1, list);
    }

    /**
     * 获取数据
     * @return
     */
    public List<String> getMenuListToCache()
    {
        return (List<String>)this.cacheManager.getCache("squaredNumber", Integer.class, Object.class).get(1);
    }

    /**
     * 删除数据
     */
    public void delMenuListToCache()
    {
        this.cacheManager.getCache("squaredNumber", Integer.class, Object.class).remove(1);
    }

}

(2)使用XML 配置

        我们再resources文件夹下创建my-config.xml文件,输入以下内容。

<config xmlns='http://www.ehcache.org/v3'>
    <cache alias="foo">
        <key-type>java.lang.Integer</key-type>
        <value-type>java.lang.String</value-type>
        <resources>
            <heap unit="entries">20</heap>
            <offheap unit="MB">10</offheap>
        </resources>
    </cache>

    <cache-template name="myDefaults">
        <key-type>java.lang.Long</key-type>
        <value-type>java.lang.String</value-type>
        <heap unit="entries">200</heap>
    </cache-template>

    <cache alias="bar" uses-template="myDefaults">
        <key-type>java.lang.Number</key-type>
    </cache>

    <cache alias="simpleCache" uses-template="myDefaults" />

</config>

        然后我们的service如下

package com.home.skydance.service;


import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.xml.XmlConfiguration;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.List;

@Service
public class CacheForXmlService {
    private CacheManager cacheManager;

    public CacheForXmlService() {
        URL myUrl = getClass().getResource("/my-config.xml");
        Configuration xmlConfig = new XmlConfiguration(myUrl);
        cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
        cacheManager.init();
    }

    /**
     * 添加数据
     * @param list
     */
    public void addMenuListToCache(String list)
    {
        this.cacheManager.getCache("foo", Integer.class, String.class).put(1, list);
    }

    /**
     * 获取数据
     * @return
     */
    public String getMenuListToCache()
    {
        return this.cacheManager.getCache("foo", Integer.class, String.class).get(1);
    }
}

3、使用Ehcache作为JCache提供者

        Java 临时缓存 API (JSR-107),也称为 JCache,是定义 javax.cache API 的规范(不是软件实现)。该规范是在 Java Community Process 下开发的,其目的是为 Java 应用程序提供标准化的缓存概念和机制。

        该 API 易于使用,它被设计为缓存标准并且与供应商无关。它消除了过去不同供应商的 API 之间存在的鲜明对比,这导致开发人员坚持使用他们已经在使用的专有 API,而不是研究新的 API,因为研究其他产品的门槛太高了。

        JavaCache(简称JCache)定义了Java标准的api。JCache主要定义了5个接口来规范缓存的生命周期

        5个接口如下:

        CacheingProvider:管理多个CacheManager,制定建立,配置,请求机制

        CacheManager:管理多个Cache,只有一个对应的   CacheProvider

        Cache:对缓存操作,只有一个对应的CacheManager

        Cache.Entry:Cache接口的内部接口,真正的存储实体

        ExporyPolicy:控制缓存的过期时间。

        下面是一个代码示例,演示了基本 JCache 配置 API 的用法:

package com.home.skydance.service;

import org.springframework.stereotype.Service;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;

@Service
public class CacheFor107Service {

    public CacheFor107Service() {
        CachingProvider provider = Caching.getCachingProvider();
        CacheManager cacheManager = provider.getCacheManager();
        MutableConfiguration<Long, String> configuration =
                new MutableConfiguration<Long, String>()
                        .setTypes(Long.class, String.class)
                        .setStoreByValue(false)
                        .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
        Cache<Long, String> cache = cacheManager.createCache("jCache", configuration);
        cache.put(1L, "one");
        String value = cache.get(1L);
        System.out.println(value);
    }
}

        从应用程序的类路径中检索默认的 CachingProvider 实现。当且仅当类路径中只有一个 JCache 实现 jar 时,此方法才有效。如果您的类路径中有多个提供程序,则使用完全限定名称org.ehcache.jsr107.EhcacheCachingProvider来检索 Ehcache 缓存提供程序。Caching.getCachingProvider(String)您可以改用静态方法来实现。

        下面是ehcache官方链接。

Ehcache 3.10 Documentation OverviewJava's most widely used cache.https://www.ehcache.org/documentation/3.10/index.htmlspringtboot and ehcachehttps://github.com/bashendixie/java_example/tree/main/ehcache

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坐望云起

如果觉得有用,请不吝打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值