এক SpringCache-ভিত্তিক ক্যাশিং সমাধান
1.1 SpringCache পরিচিতি
springcache spring3.1 সংস্করণে প্রকাশিত হয়েছিল; এটি ক্যাশের ব্যবহারকে মোড়কবদ্ধ ও বিমূর্ত করে, মেথডে annotation অ্যানোটেশন ব্যবহার করলেই ক্যাশে থাকা ফল পাওয়া যায়। ঠিক annotation ব্যবহারের কারণেই এটি ব্যবসায়িক কোড ও ক্যাশের কোডের পারস্পরিক নির্ভরতার সমস্যা সমাধান করে, অর্থাৎ ব্যবসায়িক কোডে হস্তক্ষেপ ছাড়াই বিদ্যমান কোডে সঙ্গে সঙ্গে ক্যাশের সমর্থন যোগ করে; ফলে ডেভেলপাররা আলাদাভাবে এর উপস্থিতি টের না পেয়েই ক্যাশ ব্যবহার করতে পারেন।
1.2 SpringCache-এর পরিচিতি
ক্যাশিংয়ের অনেক ফ্রেমওয়ার্ক আছে, প্রতিটির নিজস্ব সুবিধা রয়েছে, যেমন Redis、Memcached、Guava、Caffeine ইত্যাদি।
আমাদের প্রোগ্রাম ক্যাশ ব্যবহার করতে চাইলে এই ফ্রেমওয়ার্কগুলির সঙ্গে যুক্ত হতে হয়। বিচক্ষণ স্থপতিরা ইতিমধ্যেই ইন্টারফেস ব্যবহার করে এই নির্ভরতা কমাচ্ছেন, অবজেক্টমুখী বিমূর্তায়ন ও বহুরূপিতার বৈশিষ্ট্য কাজে লাগিয়ে ব্যবসায়িক কোডকে নির্দিষ্ট ফ্রেমওয়ার্ক থেকে আলাদা রাখছেন।
কিন্তু আমাদের তখনও কোডে ক্যাশ-সংক্রান্ত ইন্টারফেস ও মেথড স্পষ্টভাবে কল করতে হয়, উপযুক্ত সময়ে ক্যাশে ডেটা রাখতে হয় এবং উপযুক্ত সময়ে সেখান থেকে ডেটা পড়তে হয়। ভেবে দেখুন「AOP」এর প্রয়োগক্ষেত্র, এটা কি স্বভাবতই AOP দিয়ে করার কথা নয়?
Spring
3.1 থেকে,[@Transactional](/Transactional ) অ্যানোটেশনভিত্তিক ট্রানজ্যাকশনের অনুরূপ অ্যানোটেশনভিত্তিক ক্যাশ সমর্থন দেওয়া হয়,সেই সঙ্গে ক্যাশ অ্যাবস্ট্রাকশনও দেওয়া হয়,এর আগে সাধারণত AOP দিয়ে এটি বাস্তবায়ন করা হতো।
Spring Cache ব্যবহারের সুবিধা:
-
মৌলিক Cache অ্যাবস্ট্র্যাকশন দেয়, যাতে নিচের স্তরের বিভিন্ন Cache সহজে বদলানো যায়;
-
Cache অ্যানোটেশনের মাধ্যমে ট্রানজ্যাকশনের মতোই ক্যাশের যুক্তি স্বচ্ছভাবে আমাদের ব্যবসায়িক কোডে প্রয়োগ করা যায়,এবং তা সম্পন্ন করতে আরও কম কোড লাগে;
-
লেনদেন রোলব্যাক হলে ক্যাশও স্বয়ংক্রিয়ভাবে রোলব্যাক করার সুবিধা দেয়;
-
তুলনামূলক জটিল ক্যাশিং লজিক সমর্থন করে;

1.3 Spring Cache-এর মূল নকশা
Spring 3.1 থেকে Spring Cache, অর্থাৎ Spring-এর ক্যাশ বিমূর্তায়ন চালু করা হয়েছে। সংজ্ঞায়িত করার মাধ্যমে org.springframework.cache.Cache এবং org.springframework.cache.CacheManager ইন্টারফেস দিয়ে বিভিন্ন ক্যাশ প্রযুক্তিকে একীভূত করা হয়, এবং উন্নয়নপ্রক্রিয়া সহজ করতে JCache অ্যানোটেশন ব্যবহার সমর্থিত।
Cache ইন্টারফেস ক্যাশ কম্পোনেন্টের মাননির্দেশ নির্ধারণ করে, এতে ক্যাশের বিভিন্ন অপারেশনের সমষ্টি রয়েছে। Spring-এ Cache ইন্টারফেসের জন্য বিভিন্ন xxxCache এর বাস্তবায়ন: RedisCache , EhCacheCache , ConcurrentMapCache ইত্যাদি।
সোর্স কোডের কিছু অংশ দেখে Cache ইন্টারফেস ও CacheManager ইন্টারফেস।
Cache ইন্টারফেস
public interface Cache { //Cache名称 String getName(); //Cache负责缓存的对象 Object getNativeCache(); /** * 获取key对应的ValueWrapper * 没有对应的key,则返回null * key对应的value是null,则返回null对应的ValueWrapper */ @Nullable Cache.ValueWrapper get(Object key); //返回key对应type类型的value @Nullable <T> T get(Object key, @Nullable Class<T> type); //返回key对应的value,没有则缓存Callable::call,并返回 @Nullable <T> T get(Object key, Callable<T> valueLoader); //缓存目标key-value(替换旧值),不保证实时性 void put(Object key, @Nullable Object value); //插入缓存,并返回该key对应的value;先调用get,不存在则用put实现 @Nullable default Cache.ValueWrapper putIfAbsent(Object key, @Nullable Object value) { Cache.ValueWrapper existingValue = this.get(key); if (existingValue == null) { this.put(key, value); } return existingValue; } //删除缓存,不保证实时性 void evict(Object key); //立即删除缓存:返回false表示剔除前不存在制定key活不确定是否存在;返回true,表示该key之前存在 default boolean evictIfPresent(Object key) { this.evict(key); return false; } //清除所有缓存,不保证实时性 void clear(); //立即清楚所有缓存,返回false表示清除前没有缓存或不能确定是否有;返回true表示清除前有缓存 default boolean invalidate() { this.clear(); return false; } public static class ValueRetrievalException extends RuntimeException { @Nullable private final Object key; public ValueRetrievalException(@Nullable Object key, Callable<?> loader, Throwable ex) { super(String.format("Value for key '%s' could not be loaded using '%s'", key, loader), ex); this.key = key; } @Nullable public Object getKey() { return this.key; } } //缓存值的一个包装器接口,实现类为SimpleValueWrapper @FunctionalInterface public interface ValueWrapper { @Nullable Object get(); } }
দেখা যাচ্ছে, Cache ইন্টারফেস ক্যাশের get put evict ইত্যাদি সংশ্লিষ্ট অপারেশনকে বিমূর্তভাবে প্রকাশ করে।
AbstractValueAdaptingCache বিমূর্ত ক্লাস
public abstract class AbstractValueAdaptingCache implements Cache { //是否允许Null值 private final boolean allowNullValues; protected AbstractValueAdaptingCache(boolean allowNullValues) { this.allowNullValues = allowNullValues; } public final boolean isAllowNullValues() { return this.allowNullValues; } @Nullable public ValueWrapper get(Object key) { return this.toValueWrapper(this.lookup(key)); } @Nullable public <T> T get(Object key, @Nullable Class<T> type) { //查询到的缓存值做fromStoreValue转换 Object value = this.fromStoreValue(this.lookup(key)); //转换后非null值且无法转换为type类型则抛出异常 if (value != null && type != null && !type.isInstance(value)) { throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value); } else { return value; } } //从缓存中获取key对应的value,子类实现 @Nullable protected abstract Object lookup(Object key); //对于从缓存中获取的值,允许为空且值为NullValue时,处理为null @Nullable protected Object fromStoreValue(@Nullable Object storeValue) { return this.allowNullValues && storeValue == NullValue.INSTANCE ? null : storeValue; } //对于要插入缓存的null值,在允许null值的情况下处理为NullValue;否则抛出异常IllegalArgumentException protected Object toStoreValue(@Nullable Object userValue) { if (userValue == null) { if (this.allowNullValues) { return NullValue.INSTANCE; } else { throw new IllegalArgumentException("Cache '" + this.getName() + "' is configured to not allow null values but null was provided"); } } else { return userValue; } } //get操作依据,查询到缓存值非null,则fromStoreValue转换后包装成SimpleValueWrapper返回 @Nullable protected ValueWrapper toValueWrapper(@Nullable Object storeValue) { return storeValue != null ? new SimpleValueWrapper(this.fromStoreValue(storeValue)) : null; } }
বিমূর্ত ক্লাস AbstractValueAdaptingCache Cache ইন্টারফেস বাস্তবায়ন করেছে, মূলত NULL মান প্রক্রিয়াকরণের যুক্তিকে বিমূর্ত রূপ দিয়েছে।
-
allowNullValuesঅ্যাট্রিবিউটটি নির্দেশ করে NULL মান ক্যাশ করার অনুমতি আছে কি না -
fromStoreValueপদ্ধতি দিয়ে NULL মান প্রক্রিয়াকরণেরgetঅপারেশন, প্রপার্টিতেallowNullValuestrue হলে, NullValue-কে NULL হিসেবে প্রক্রিয়াকরণ করুন -
toStoreValueমেথড দিয়ে NULL মান প্রক্রিয়াকরণেরputঅপারেশন, প্রপার্টিতেallowNullValuestrue হলে NULL-কে NullValue হিসেবে প্রক্রিয়াকরণ করা হয়, অন্যথায় ব্যতিক্রম ছোড়া হয় -
toValueWrapperমেথড প্রদান করেCacheইন্টারফেসেgetমেথডের ডিফল্ট বাস্তবায়ন,ক্যাশ থেকে মান পড়ে,তারপর এর মাধ্যমেfromStoreValueরূপান্তর, শেষে মোড়কবদ্ধ করা হয়SimpleValueWrapperফেরত দেয় -
ValueWrapper get(Object key)এবংT get(Object key, @Nullable Classtype)পদ্ধতিটি উপরের পদ্ধতির ভিত্তিতে বাস্তবায়িত -
ValueWrapper get(Object key)এবং@Nullable Classtype)পদ্ধতিটি উপরের পদ্ধতির ভিত্তিতে বাস্তবায়িত -
lookupবিমূর্ত মেথডটি সাবক্লাসকে প্রকৃত ক্যাশের মান পেতে সাহায্য করে
ConcurrentMapCache
public class ConcurrentMapCache extends AbstractValueAdaptingCache { private final String name; //定义ConcurrentMap缓存 private final ConcurrentMap<Object, Object> store; //如果要缓存的是值对象的copy,则由此序列化代理类处理 @Nullable private final SerializationDelegate serialization; public ConcurrentMapCache(String name) { this(name, new ConcurrentHashMap(256), true); } //默认允许处理null public ConcurrentMapCache(String name, boolean allowNullValues) { this(name, new ConcurrentHashMap(256), allowNullValues); } //默认serialization = null public ConcurrentMapCache(String name, ConcurrentMap<Object, Object> store, boolean allowNullValues) { this(name, store, allowNullValues, (SerializationDelegate)null); } protected ConcurrentMapCache(String name, ConcurrentMap<Object, Object> store, boolean allowNullValues, @Nullable SerializationDelegate serialization) { super(allowNullValues); Assert.notNull(name, "Name must not be null"); Assert.notNull(store, "Store must not be null"); this.name = name; this.store = store; this.serialization = serialization; } //serialization不为空,缓存值对象的copy public final boolean isStoreByValue() { return this.serialization != null; } public final String getName() { return this.name; } public final ConcurrentMap<Object, Object> getNativeCache() { return this.store; } //实现lookup:store#get @Nullable protected Object lookup(Object key) { return this.store.get(key); } //基于ConcurrentMap::computeIfAbsent方法实现;get和put的值由fromStoreValue和toStoreValue处理Null @Nullable public <T> T get(Object key, Callable<T> valueLoader) { return this.fromStoreValue(this.store.computeIfAbsent(key, (k) -> { try { return this.toStoreValue(valueLoader.call()); } catch (Throwable var5) { throw new ValueRetrievalException(key, valueLoader, var5); } })); } public void put(Object key, @Nullable Object value) { this.store.put(key, this.toStoreValue(value)); } @Nullable public ValueWrapper putIfAbsent(Object key, @Nullable Object value) { Object existing = this.store.putIfAbsent(key, this.toStoreValue(value)); return this.toValueWrapper(existing); } public void evict(Object key) { this.store.remove(key); } public boolean evictIfPresent(Object key) { return this.store.remove(key) != null; } public void clear() { this.store.clear(); } public boolean invalidate() { boolean notEmpty = !this.store.isEmpty(); this.store.clear(); return notEmpty; } protected Object toStoreValue(@Nullable Object userValue) { Object storeValue = super.toStoreValue(userValue); if (this.serialization != null) { try { return this.serialization.serializeToByteArray(storeValue); } catch (Throwable var4) { throw new IllegalArgumentException("Failed to serialize cache value '" + userValue + "'. Does it implement Serializable?", var4); } } else { return storeValue; } } protected Object fromStoreValue(@Nullable Object storeValue) { if (storeValue != null && this.serialization != null) { try { return super.fromStoreValue(this.serialization.deserializeFromByteArray((byte[])((byte[])storeValue))); } catch (Throwable var3) { throw new IllegalArgumentException("Failed to deserialize cache value '" + storeValue + "'", var3); } } else { return super.fromStoreValue(storeValue); } } }
ConcurrentMapCache অ্যাবস্ট্রাক্ট ক্লাস থেকে উত্তরাধিকার নিয়েছে AbstractValueAdaptingCache ,এটি Spring-এর ডিফল্ট ক্যাশ বাস্তবায়ন। এটি ক্যাশ করা অবজেক্টের অনুলিপি ক্যাশে রাখার সুবিধা দেয়,SerializationDelegate
serialization দিয়ে সিরিয়ালাইজেশন করা হয়,ডিফল্ট মান null অর্থাৎ রেফারেন্সভিত্তিক ক্যাশ। ক্যাশসংক্রান্ত কাজগুলি যে বেস ক্লাসের ওপর ভিত্তি করে AbstractValueAdaptingCache এর
null মানের ব্যবস্থাপনা, ডিফল্টভাবে null অনুমোদিত।
CacheManager
public interface CacheManager { @Nullable //获取指定name的Cache,可能延迟创建 Cache getCache(String name); //获取当前CacheManager下的Cache name集合 Collection<String> getCacheNames(); }
CacheManager এর ভিত্তিতে
name দিয়ে একগুচ্ছ Cache পরিচালনা করে। অবশ্য, CacheManager এরও অনেক বাস্তবায়নকারী ক্লাস আছে, যেমন ConcurrentMapCacheManager 、 AbstractCacheManager ও SimpleCacheManager , এগুলো xxxCacheManager ক্লাসগুলো সবই Cache পরিচালনার নিয়ম নির্ধারণের জন্য, তাই এখানে আর বিস্তারিত আলোচনা করা হচ্ছে না।
দুই SpringCache ব্যবহার
2.1 কীভাবে ব্যবহার করবেন
Spring Cache এমনই একটি ফ্রেমওয়ার্ক। এটি AOP ব্যবহার করে অ্যানোটেশনভিত্তিক ক্যাশিং বাস্তবায়ন করে এবং যথাযথ বিমূর্তীকরণ প্রদান করে। ফলে নিচে কোন ক্যাশিং ফ্রেমওয়ার্ক ব্যবহার হচ্ছে তা নিয়ে ব্যবসায়িক কোডকে ভাবতে হয় না; শুধু একটি অ্যানোটেশন যোগ করলেই ক্যাশিং কার্যকারিতা পাওয়া যায়।
ডিপেন্ডেন্সি যোগ করুন
<!--springboot的cache支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!--配置拓展还需添加的依赖--> <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.9.2</version> </dependency>
Cache কনফিগার করুন
Application-এর স্টার্টআপ ক্লাসে @EnableCaching অ্যানোটেশন যোগ করুন
@SpringBootApplication @MapperScan("com.xxxx.dao") @EnableCaching public class AxxxxApplication { public static void main(String[] args) { SpringApplication.run(AxxxxApplication.class, args); } }
cache-এর ক্যাশের ধরন কনফিগার করা; এখানে মূলত স্থানীয় ক্যাশের পরিচয় দেওয়া হচ্ছে
//方式一:ConcurrentMapCache (不好设置过期时间) @Configuration public class SpringCachingConfig { @Bean public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); Set<ConcurrentMapCache> mapCaches=new HashSet<>(); //配置cache类型与目录 mapCaches.add(new ConcurrentMapCache("cacheNames1")); mapCaches.add(new ConcurrentMapCache("cacheNames2")); mapCaches.add(new ConcurrentMapCache("cacheNames3")); mapCaches.add(new ConcurrentMapCache("cacheNames4")); cacheManager.setCaches(mapCaches); cacheManager.afterPropertiesSet(); return cacheManager; } } //方式二:CaffeineCache (可设置过期时间) @Configuration public class SpringCachingConfig { @Bean public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); List<CaffeineCache> caffeineCaches = new ArrayList<>(); //SysConstants.CACHE_NAMES=new ArrayList( //Arrays.asList("cacheNames1","cacheNames2","cacheNames3","cacheNames4") //); for (String cacheName: SysConstants.CACHE_NAMES) { caffeineCaches.add(new CaffeineCache(cacheName, Caffeine.newBuilder() .initialCapacity(50) .maximumSize(30000)//最大存储数量 .expireAfterWrite(2, TimeUnit.HOURS)//过期时间2 小时 .build())); } cacheManager.setCaches(caffeineCaches); return cacheManager; } } //方式三。。。。还可以配置redis以及其他的方式,这里主要介绍以上两种方式
ইন্টারফেসে ক্যাশিং বাস্তবায়ন
//控制器1 @RestController @RequestMapping("/path1") @Cacheable(cacheNames = "cacheNames1" ,key="#root.methodName+#a0" ) public class Controller1 { } //控制器2 @RestController @RequestMapping("/path2") @Cacheable(cacheNames = "cacheNames2" ,key="#root.methodName+#a0" ) public class Controller2 { } //控制器3 @RestController @RequestMapping("/path3") @Cacheable(cacheNames = "cacheNames3" ,key="#root.methodName+#a0" ) public class Controller3 { } //控制器4 @RestController @RequestMapping("/path4") @Cacheable(cacheNames = "cacheNames4" ,key="#root.methodName+#a0" ) public class Controller4 { }
2.2 SpringCache অ্যানোটেশনের বিস্তারিত ব্যাখ্যা
@Cacheable অ্যানোটেশন
ক্যাশে না থাকলে:ডেটাবেসে অনুসন্ধান করুন, ক্যাশে সংরক্ষণ করুন, ফলাফল ফেরত দিন,
ক্যাশে থাকলে:সরাসরি ফলাফল ফেরত দিন
| প্যারামিটার | ব্যাখ্যা | উদাহরণ |
| value | ক্যাশের নাম, যা spring কনফিগারেশন ফাইলে সংজ্ঞায়িত থাকে; অন্তত একটি নির্দিষ্ট করতেই হবে |
উদাহরণস্বরূপ: @Cacheable(value=”mycache”) @Cacheable(value={”cache1”,”cache2”} |
| কী | ক্যাশের key, খালি রাখা যায়। নির্দিষ্ট করলে SpEL এক্সপ্রেশন অনুযায়ী লিখতে হবে; নির্দিষ্ট না করলে ডিফল্টভাবে মেথডের সব প্যারামিটার একত্র করে তৈরি করা হয় | @Cacheable(value=”testcache”,key=”#userName”) |
| শর্ত | ক্যাশ করার শর্ত,খালি রাখা যায়,SpEL দিয়ে লেখা হয়,ফল হিসেবে দেয় true অথবা false,শুধু true হলেই ক্যাশ করা হয় | @Cacheable(value=”testcache”,condition=”#userName.length()>2”) |
কাজ:ক্যাশে লেখার জন্য ব্যবহার করা যায়,ফলাফল ক্যাশে সংরক্ষণ করা হয়,যাতে পরবর্তী কলের সময় সরাসরি ক্যাশের মান ফেরত দেওয়া যায়,আসল মেথডটি আবার চালাতে না হয়। সবচেয়ে সহজ ব্যবহারপদ্ধতি,অ্যানোটেশনের নাম=ক্যাশের নাম,ব্যবহারের উদাহরণ নিচে:
@Cacheable(value="accountCache")// 使用了一个缓存名叫 accountCache public Account getAccountByName(String userName) { // 方法内部实现不考虑缓存逻辑,直接实现业务 System.out.println("real query account."+userName); return getFromDB(userName); }
@CacheEvict অ্যানোটেশন
@CacheEvict:ক্যাশ মুছে দেওয়ার অ্যানোটেশন, পুরোনো ও অপ্রয়োজনীয় তথ্য মুছতে এটি খুবই উপযোগী। এখানে আরও একটি প্যারামিটার(allEntries) রয়েছে, allEntries=true সেট করলে সব এন্ট্রি একসঙ্গে মুছে দেওয়া যায়
| প্যারামিটার | ব্যাখ্যা | উদাহরণ |
| value | ক্যাশের নাম, যা spring কনফিগারেশন ফাইলে সংজ্ঞায়িত থাকে; অন্তত একটি নির্দিষ্ট করতেই হবে | @CacheEvict(value=”my cache”) |
| কী | ক্যাশের key, খালি রাখা যায়। নির্দিষ্ট করলে SpEL এক্সপ্রেশন অনুযায়ী লিখতে হবে; নির্দিষ্ট না করলে ডিফল্টভাবে মেথডের সব প্যারামিটার একত্র করে তৈরি করা হয় | @CacheEvict(value=”testcache”,key=”#userName”) |
| শর্ত | ক্যাশ করার শর্ত,খালি রাখা যায়,SpEL দিয়ে লেখা হয়,ফল হিসেবে দেয় true অথবা false,শুধু true হলেই ক্যাশ করা হয় | @CacheEvict(value=”testcache”,condition=”#userName.length()>2”) |
| allEntries | ক্যাশের সমস্ত বিষয়বস্তু মুছে ফেলা হবে কি না, ডিফল্ট হলো false,true নির্দিষ্ট করলে, মেথড কলের পরই সমস্ত ক্যাশ মুছে ফেলা হবে | @CachEvict(value=”testcache”,allEntries=true) |
| beforeInvocation | মেথড চালানোর আগেই ক্যাশ খালি করা হবে কি না, তার ডিফল্ট মান false। true নির্ধারণ করলে মেথড চালানোর আগেই ক্যাশ খালি করা হয়। ডিফল্ট অবস্থায় মেথড চালাতে গিয়ে ব্যতিক্রম ঘটলে ক্যাশ খালি করা হয় না | @CachEvict(value=”testcache”,beforeInvocation=true) |
@CacheEvict(value="accountCache",key="#account.getName()")// 清空accountCache 缓存 public void updateAccount(Account account) { updateDB(account); } @CacheEvict(value="accountCache",allEntries=true)// 清空accountCache 缓存 public void reload() { reloadAll() } @Cacheable(value="accountCache",condition="#userName.length() <=4")// 缓存名叫 accountCache public Account getAccountByName(String userName) { // 方法内部实现不考虑缓存逻辑,直接实现业务 return getFromDB(userName); }
@CachePut অ্যানোটেশন
@CachePut:মেথডের কার্যক্রমে ব্যাঘাত না ঘটিয়ে ক্যাশ হালনাগাদ করার প্রয়োজন হলে,এই অ্যানোটেশন ব্যবহার করা যায়。অর্থাৎ,মেথডটি প্রতিবার নির্বাহ করা হয়,এবং ফলাফল ক্যাশে রাখা হয়;
| প্যারামিটার | ব্যাখ্যা | উদাহরণ |
| value | ক্যাশের নাম, যা spring কনফিগারেশন ফাইলে সংজ্ঞায়িত থাকে; অন্তত একটি নির্দিষ্ট করতেই হবে | @CachePut(value=”my cache”) |
| কী | ক্যাশের key, খালি রাখা যায়। নির্দিষ্ট করলে SpEL এক্সপ্রেশন অনুযায়ী লিখতে হবে; নির্দিষ্ট না করলে ডিফল্টভাবে মেথডের সব প্যারামিটার একত্র করে তৈরি করা হয় | @CachePut(value=”testcache”,key=”#userName”) |
| শর্ত | ক্যাশ করার শর্ত,খালি রাখা যায়,SpEL দিয়ে লেখা হয়,ফল হিসেবে দেয় true অথবা false,শুধু true হলেই ক্যাশ করা হয় | @CachePut(value=”testcache”,condition=”#userName.length()>2”) |
@CachePut অ্যানোটেশন, এই অ্যানোটেশন মেথড চালানো নিশ্চিত করে এবং একই সঙ্গে মেথডের ফেরত দেওয়া মান ক্যাশেও সংরক্ষণ করে, ফলে ক্যাশ ও ডেটাবেস একসঙ্গে হালনাগাদ হয়।
@CachePut(value="accountCache",key="#account.getName()")// 更新accountCache 缓存 public Account updateAccount(Account account) { return updateDB(account); }
@Caching অ্যানোটেশন
ক্যাশ ব্যবহারের সময় একই সঙ্গে আপডেট ও মুছে ফেলার প্রয়োজন হতে পারে, ফলে একাধিক অ্যানোটেশন একসঙ্গে ব্যবহার করার পরিস্থিতি তৈরি হয়.আর @Caching দিয়ে করা যায়
//添加user缓存的同时,移除userPage的缓存 @Caching( put =@CachePut(value = "user",key ="#userVo.id"), evict = @CacheEvict(value = "userPage",allEntries = true) )
@Caching(put = { @CachePut(value = "user", key = "#user.id"), @CachePut(value = "user", key = "#user.username"), @CachePut(value = "user", key = "#user.email") }) public User save(User user) {
@CacheConfig
প্রতিটি @Cacheable()-এর মধ্যে value=“xxx” নামের একটি প্রপার্টি থাকে, স্পষ্টতই মেথড বেশি হলে বারবার এটি লেখা বেশ ক্লান্তিকর, একবারেই সব ঘোষণা করা গেলে সুবিধা হতো, তাই @CacheConfig কনফিগারেশনটি এসেছে, @CacheConfig হলো ক্লাস স্তরের একটি অ্যানোটেশন, যা ক্যাশের নামগুলো ভাগ করে ব্যবহার করতে দেয়, আপনি কোনো মেথডে অন্য নাম লিখলে, তখনও মেথডে দেওয়া নামই প্রাধান্য পাবে।
@CacheConfig("books") public class BookRepositoryImpl implements BookRepository { @Cacheable public Book findBook(ISBN isbn) {...} }
শর্তসাপেক্ষ ক্যাশিং
নিচে কিছু প্রচলিত শর্তাধীন ক্যাশিং দেওয়া হলো
//@Cacheable将在执行方法之前( #result还拿不到返回值)判断condition,如果返回true,则查缓存; @Cacheable(value = "user", key = "#id", condition = "#id lt 10") public User conditionFindById(final Long id) //@CachePut将在执行完方法后(#result就能拿到返回值了)判断condition,如果返回true,则放入缓存; @CachePut(value = "user", key = "#id", condition = "#result.username ne 'zhang'") public User conditionSave(final User user) //@CachePut将在执行完方法后(#result就能拿到返回值了)判断unless,如果返回false,则放入缓存;(即跟condition相反) @CachePut(value = "user", key = "#user.id", unless = "#result.username eq 'zhang'") public User conditionSave2(final User user) //@CacheEvict, beforeInvocation=false表示在方法执行之后调用(#result能拿到返回值了);且判断condition,如果返回true,则移除缓存; @CacheEvict(value = "user", key = "#user.id", beforeInvocation = false, condition = "#result.username ne 'zhang'") public User conditionDelete(final User user)
কাস্টম ক্যাশ অ্যানোটেশন
যেমন আগের @Caching সমন্বয়টি মেথডের ওপর অ্যানোটেশনগুলো বসানোর ফলে পুরো কোডকে বেশ এলোমেলো দেখায়; তখন কাস্টম অ্যানোটেশন ব্যবহার করে এই অ্যানোটেশনগুলোকে একটি অ্যানোটেশনে একত্র করা যায়, যেমন:
@Caching(put = { @CachePut(value = "user", key = "#user.id"), @CachePut(value = "user", key = "#user.username"), @CachePut(value = "user", key = "#user.email") }) @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface UserSaveCache { }
এভাবে মেথডে নিচের কোড ব্যবহার করলেই চলে, পুরো কোডও বেশ পরিচ্ছন্ন দেখায়।
@UserSaveCache public User save(User user)
সম্প্রসারণ
যেমন findByUsername-এর সময়, শুধু username–>user রাখা উচিত নয়, সঙ্গে id—>user এবং email—>user-ও রাখতে হবে;এতে পরের বার id দিয়ে খুঁজলে সরাসরি ক্যাশেই ফল পাওয়া যাবে
@Caching( cacheable = { @Cacheable(value = "user", key = "#username") }, put = { @CachePut(value = "user", key = "#result.id", condition = "#result != null"), @CachePut(value = "user", key = "#result.email", condition = "#result != null") } ) public User findByUsername(final String username) { System.out.println("cache miss, invoke find by username, username:" + username); for (User user : users) { if (user.getUsername().equals(username)) { return user; } } return null; }
আসলে:id—>user;username—->user;email—>user;এর ক্ষেত্রে আরও ভালো উপায় হতে পারে:id—>user;username—>id;email—>id;যাতে user-এর একটিমাত্র কপি সংরক্ষিত থাকে;যেমন:
@CachePut(value="cacheName", key="#user.username", cacheValue="#user.username") public void save(User user) @Cacheable(value="cacheName", key="#user.username", cacheValue="#caches[0].get(#caches[0].get(#username).get())") public User findByUsername(String username)
SpEL কনটেক্সট ডেটা
Spring Cache আমাদের ব্যবহারের জন্য কিছু SpEL কনটেক্সট ডেটা দেয়,নিচের সারণিটি সরাসরি Spring-এর আনুষ্ঠানিক নথি থেকে নেওয়া:
| নাম | অবস্থান | বিবরণ | উদাহরণ |
| methodName | root অবজেক্ট | বর্তমানে কল করা মেথডের নাম | root.methodName |
| method | root অবজেক্ট | বর্তমানে যে মেথডটি কল করা হচ্ছে | root.method.name |
| target | root অবজেক্ট | বর্তমানে যে লক্ষ্য অবজেক্টকে কল করা হচ্ছে | root.target |
| targetClass | root অবজেক্ট | বর্তমানে কল করা লক্ষ্য অবজেক্টের ক্লাস | root.targetClass |
| args | root অবজেক্ট | বর্তমানে কল করা মেথডের প্যারামিটার তালিকা | root.args[0] |
| caches | root অবজেক্ট | বর্তমান মেথড কলের ব্যবহৃত ক্যাশের তালিকা(যেমন @Cacheable(value={“cache1”, “cache2”})),এ ক্ষেত্রে দুটি ক্যাশ থাকে | root.caches[0].name |
| আর্গুমেন্টের নাম | নির্বাহের প্রসঙ্গ | বর্তমানে কল করা মেথডের প্যারামিটার, যেমন findById(Long id),আমরা #id দিয়ে প্যারামিটারটি পেতে পারি | user.id |
| ফলাফল | নির্বাহের প্রসঙ্গ | মেথড কার্যকর হওয়ার পরের রিটার্ন মান(কেবল মেথড কার্যকর হওয়ার পর মূল্যায়িত শর্তের ক্ষেত্রে প্রযোজ্য, যেমন ‘unless', 'cache evict'-এর beforeInvocation=false) | ফলাফল |
@CacheEvict(value = "user", key = "#user.id", condition = "#root.target.canCache() and #root.caches[0].get(#user.id).get().username ne #user.username", beforeInvocation = true) public void conditionUpdate(User user)
সারসংক্ষেপ
ক্যাশ ঘোষণার জন্য spring-এর ক্যাশ ব্যবস্থা একগুচ্ছ java অ্যানোটেশন সরবরাহ করে:
· @Cacheable
o
কার্যকারিতা:ক্যাশে লেখা চালু করে, ক্যাশে না থাকলে ডেটাবেসে অনুসন্ধান করে, ক্যাশে সংরক্ষণ করে, ফলাফল ফেরত দেয়, ক্যাশে থাকলে সরাসরি ফলাফল ফেরত দেয়
o প্রয়োগ:ডেটাবেসে অনুসন্ধান পদ্ধতি
· @CacheEvict
o
কাজ:ক্যাশ পরিষ্কার করার প্রক্রিয়া চালু করা
o প্রয়োগ:ডেটাবেস মুছে ফেলা বা পরিবর্তন করাপদ্ধতি
· @CachePut
o
কার্যকারিতা:ক্যাশে লেখা(মেথডের কার্যক্রমকে প্রভাবিত করে না)。
o প্রয়োগ:ডেটাবেসে নতুন করে যোগ করুন পদ্ধতি
· @ক্যাশিং
o
কাজ:মেথডে প্রয়োগ করার জন্য একাধিক ক্যাশ অপারেশন নতুন করে একত্র করা
o প্রয়োগ:ওপরের অ্যানোটেশনগুলো একসঙ্গে ব্যবহার করা