ToB企服应用市场:ToB评测及商务社交产业平台

标题: JCache 介绍 [打印本页]

作者: 涛声依旧在    时间: 2024-5-14 11:26
标题: JCache 介绍
JCache 是 Java 官方的缓存规范即 JSR107,主要明白了Java 中基于内存进行对象缓存的一些要求,涵盖对象的创建、查询、更新、删除、一致性保证等方面内容;本文主要介绍其基本概念及简单使用。
1、JCache 简介

1.1、核心概念

JCache 中定义了五个核心接口:CachingProvider、CacheManager、Cache、Entry 和 ExpiryPolicy。
A、CachingProvider 用于创建、配置、获取、管理和控制零个或多个 CacheManager;应用程序在运行时可以访问或使用零个或多个 CachingProvider。
B、CacheManager 用于创建、配置、获取、管理和控制零个或多个唯一命名的 Cache,这些 Cache 存在于 CacheManager 的上下文中;一个 CacheManager 只能归属一个 CachingProvider。
C、Cache 是类似 Map 的数据布局,用于临时存储基于 key 的 value;一个 Cache 只能归属一个 CacheManager。
D、Entry 是存储在 Cache 中的键值对。
E、ExpiryPolicy 定义了每个 Entry 在 Cache 中有用时间(TTL),有用期内 Entry 可以或许被访问、修改和删除,有用期后该 Entry 不能在被访问、修改和删除。
对应关系如下:

1.2、相关注解

JSR107 将一些常用的 API 方法封装为注解,使用注解来简化编码的复杂度,低落缓存对于业务逻辑的侵入性,使得业务开发人员更加专注于业务本身的开发。
注解说明@CacheResult将指定的 key 和 value 存入到缓存容器中@CachePut更新缓存容器中对应 key 的缓存内容@CacheRemove移除缓存容器中对应 key 的缓存记录@CacheRemoveAll移除缓存容器中的所有缓存记录@CacheKey指定缓存的 key,用于方法参数前面@CacheValue指定缓存的 value,用于方法参数前面上述注解主要是添加在方法上面,用于自动将方法的入参与返回结果之间进行一个映射与自动缓存,对于后续请求如果命中缓存则直接返回缓存结果而无需再次实行方法的详细处理,以此来提拔接口的响应速度与承压本领。
1.3、值存储和引用存储

JSR-107 中定义了两种存储 Entry 的方法,即按值存储(Store-By-Value)和按引用存储(Store-By-Reference)。
• 按值存储是默认机制,也就是在存储键值对时,先对 key 和 value 进行拷贝,然后将拷贝的副本存储到 Cache 中;当访问 Cache 时,返回的是数据的副本。
• 按引用存储是别的一种可选的机制,存储键值对时,Cache 中存储的是 key 和 value 的引用。当应用程序修改键值对时,应用程序无需再次修改 Cache 中的数据。
1.4、一致性

一致性是指当并发访问缓存时,需要保证修改的可见性在并发线程/历程间是一致的。为了保证一致性,所有的实现框架都应该支持默认一致性模子:
在实行大部分 Cache 操作时,就好像为 Cache 中的每个 key 加了锁,当某个操作获取该 key 的排它性读写锁时,后面对该 key 的所有操作都会被阻塞,直到这个锁释放。注意,这里的操作可以是单个 JVM 历程内的,也可以是跨 JVM 的操作。对于某些具有返回值的 Cache 操作,返回的缓存值需要是最新值。但是这个最新值,可以根据缓存的详细实现定义,比如当并发修改时,这个返回值可以是修改前的值,也可以是修改后的值。
1.5、Cache 和 Map 的差别

相同点:
不同点:
2、JCache 使用

JCache 只是定义了一组接口,要使用还需引入详细的实现框架。
2.1、Caffeine 中使用 JCache

2.1.1、引入依靠
  1. <dependency>
  2.     <groupId>javax.cache</groupId>
  3.     <artifactId>cache-api</artifactId>
  4.     <version>1.1.1</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>com.github.ben-manes.caffeine</groupId>
  8.     <artifactId>jcache</artifactId>
  9.     <version>2.9.3</version>
  10. </dependency>
复制代码
2.1.2、简单使用
  1. @Test
  2. public void caffeine() {
  3.     CachingProvider cachingProvider = Caching.getCachingProvider("com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider");
  4.     CacheManager cacheManager = cachingProvider.getCacheManager();
  5.     MutableConfiguration<Integer, String> mutableConfiguration = new MutableConfiguration<Integer, String>()
  6.             .setTypes(Integer.class, String.class)
  7.             .setStoreByValue(false)
  8.             .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 5)));
  9.     Cache<Integer, String> myCache = cacheManager.createCache("myCache", mutableConfiguration);
  10.     myCache.put(1, "aaa");
  11.     log.info(myCache.get(1));
  12.     cacheManager.close();
  13. }
复制代码
2.2、Ehcache3 中使用 JCache

2.2.1、引入依靠
  1. <dependency>
  2.     <groupId>javax.cache</groupId>
  3.     <artifactId>cache-api</artifactId>
  4.     <version>1.1.1</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>org.ehcache</groupId>
  8.     <artifactId>ehcache</artifactId>
  9.     <version>3.10.8</version>
  10.     <exclusions>
  11.         <exclusion>
  12.             <groupId>org.glassfish.jaxb</groupId>
  13.             <artifactId>jaxb-runtime</artifactId>
  14.         </exclusion>
  15.     </exclusions>
  16. </dependency>
复制代码
2.2.2、简单使用
  1. @Test
  2. public void ehcache3() {
  3.     CachingProvider cachingProvider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
  4.     CacheManager cacheManager = cachingProvider.getCacheManager();
  5.     MutableConfiguration<Integer, String> mutableConfiguration = new MutableConfiguration<Integer, String>()
  6.             .setTypes(Integer.class, String.class)
  7.             .setStoreByValue(false)
  8.             .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 5)));
  9.     Cache<Integer, String> myCache = cacheManager.createCache("myCache", mutableConfiguration);
  10.     log.info(myCache.getClass().getName() + "|" + myCache.getClass().getCanonicalName());
  11.     myCache.put(1, "aaa");
  12.     log.info(myCache.get(1));
  13.     cacheManager.close();
  14. }
复制代码
 Caffeine 及 Ehcache3 中使用 JCache 的完整代码:
  1. package com.abc.demo.cache;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.junit.Test;
  4. import javax.cache.Cache;
  5. import javax.cache.CacheManager;
  6. import javax.cache.Caching;
  7. import javax.cache.configuration.MutableConfiguration;
  8. import javax.cache.expiry.CreatedExpiryPolicy;
  9. import javax.cache.expiry.Duration;
  10. import javax.cache.spi.CachingProvider;
  11. import java.util.concurrent.TimeUnit;
  12. @Slf4j
  13. public class JCacheCase {
  14.     @Test
  15.     public void caffeine() {
  16.         CachingProvider cachingProvider = Caching.getCachingProvider("com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider");
  17.         CacheManager cacheManager = cachingProvider.getCacheManager();
  18.         MutableConfiguration<Integer, String> mutableConfiguration = new MutableConfiguration<Integer, String>()
  19.                 .setTypes(Integer.class, String.class)
  20.                 .setStoreByValue(false)
  21.                 .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 5)));
  22.         Cache<Integer, String> myCache = cacheManager.createCache("myCache", mutableConfiguration);
  23.         myCache.put(1, "aaa");
  24.         log.info(myCache.get(1));
  25.         cacheManager.close();
  26.     }
  27.     @Test
  28.     public void ehcache3() {
  29.         CachingProvider cachingProvider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
  30.         CacheManager cacheManager = cachingProvider.getCacheManager();
  31.         MutableConfiguration<Integer, String> mutableConfiguration = new MutableConfiguration<Integer, String>()
  32.                 .setTypes(Integer.class, String.class)
  33.                 .setStoreByValue(false)
  34.                 .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 5)));
  35.         Cache<Integer, String> myCache = cacheManager.createCache("myCache", mutableConfiguration);
  36.         log.info(myCache.getClass().getName() + "|" + myCache.getClass().getCanonicalName());
  37.         myCache.put(1, "aaa");
  38.         log.info(myCache.get(1));
  39.         cacheManager.close();
  40.     }
  41. }
复制代码
JCacheCase.java2.3、SpringBoot 中 JCache 注解使用

2.3.1、引入依靠

这里使用 Caffeine 作为 JCache 的实现框架。
  1. <parent>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-parent</artifactId>
  4.     <version>2.7.18</version>
  5.     <relativePath />
  6. </parent>
  7. <dependencies>
  8.     <dependency>
  9.         <groupId>org.springframework.boot</groupId>
  10.         <artifactId>spring-boot-starter-web</artifactId>
  11.     </dependency>
  12.     <dependency>
  13.         <groupId>org.springframework.boot</groupId>
  14.         <artifactId>spring-boot-starter-cache</artifactId>
  15.     </dependency>
  16.     <dependency>
  17.         <groupId>com.github.ben-manes.caffeine</groupId>
  18.         <artifactId>jcache</artifactId>
  19.     </dependency>
  20. </dependencies>
复制代码
2.3.2、配置缓存名称
  1. spring:
  2.   cache:
  3.     type: jcache
  4.     cacheNames: myCache
复制代码
2.3.3、启用缓存

启动类上增加 @EnableCaching 注解。
  1. @SpringBootApplication
  2. @EnableCaching
  3. public class DemoApplication {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(DemoApplication.class, args);
  6.     }
  7. }
复制代码
2.3.4、JCache 注解使用
  1. package com.abc.general.service.impl;
  2. import com.abc.general.service.ICacheService;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.stereotype.Service;
  5. import javax.cache.annotation.*;
  6. @Slf4j
  7. @Service
  8. public class CacheServiceImpl implements ICacheService {
  9.     @CacheResult(cacheName = "myCache")
  10.     @Override
  11.     public String queryById(@CacheKey int id) {
  12.         log.info("queryById,id={}", id);
  13.         return "value" + id;
  14.     }
  15.     @CachePut(cacheName = "myCache")
  16.     @Override
  17.     public String updateById(@CacheKey int id, @CacheValue String newValue) {
  18.         log.info("updateById,id={},newValue={}", id, newValue);
  19.         return newValue;
  20.     }
  21.     @CacheRemove(cacheName = "myCache")
  22.     @Override
  23.     public void deleteById(@CacheKey int id) {
  24.         log.info("deleteById,id={}", id);
  25.     }
  26. }
复制代码
 
 
参考:https://developer.aliyun.com/article/786959。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4