一、多層快取
1. 傳統快取方案
請求到達tomcat後,先去redis中取得緩存,不命中則去mysql取得
2. 多層快取方案
tomcat
的請求並發數,是遠小於redis的,因此tomcat會變成瓶頸利用請求處理每個環節,分別加入緩存,減輕tomcat壓力,提升服務效能
- 優點: 儲存容量大,可靠度好,可在叢集中共用進程本地緩存, 如HashMap, GuavaCache- 缺點:存取快取有網路開銷
- 場景: 快取資料量大,可靠度高,需要在叢集中共享的資料
- 優點:讀取本地內存,沒有網路開銷,速度更快- 缺點:儲存容量有限,可靠性低(如重啟後遺失),無法在集群中共享
1. 實用案例
- 場景:效能要求高,快取資料量少
- Caffeine是一個基於java8開發的,提供了近乎最佳命中率的高效能的本機快取庫
- 目前spring內部的快取用的就是這個
-
<dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>3.0.5</version> </dependency>
package com.erick.cache; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import java.time.Duration; public final class CacheUtil { private static int expireSeconds = 2; public static Cache<String, String> cacheWithExpireSeconds; private static int maxPairs = 1; public static Cache<String, String> cacheWithMaxPairs; static { /*过期策略,写完60s后过期*/ cacheWithExpireSeconds = Caffeine.newBuilder() .expireAfterWrite(Duration.ofSeconds(expireSeconds)) .build(); /*过期策略,达到最大值后删除 * 1. 并不会立即删除,等一会儿才会删除 * 2. 会将之前存储的数据删除掉*/ cacheWithMaxPairs = Caffeine.newBuilder() .maximumSize(maxPairs) .build(); } /*从缓存中获取数据 * 1. 如果缓存中有,则直接从缓存中返回 * 2. 如果缓存中没有,则去数据查询并返回结果*/ public static String getKeyWithExpire(String key) { return cacheWithExpireSeconds.get(key, value -> { return getResultFromDB(); }); } public static String getKeyWithMaxPair(String key) { return cacheWithMaxPairs.get(key, value -> { return getResultFromDB(); }); } private static String getResultFromDB() { System.out.println("数据库查询"); return "db result"; } }
package com.erick.cache; import java.util.concurrent.TimeUnit; public class Test { @org.junit.Test public void test01() throws InterruptedException { CacheUtil.cacheWithExpireSeconds.put("name", "erick"); System.out.println(CacheUtil.getKeyWithExpire("name")); TimeUnit.SECONDS.sleep(3); System.out.println(CacheUtil.getKeyWithExpire("name")); } @org.junit.Test public void test02() throws InterruptedException { CacheUtil.cacheWithMaxPairs.put("name", "erick"); CacheUtil.cacheWithMaxPairs.put("age", "12"); System.out.println(CacheUtil.getKeyWithMaxPair("name")); System.out.println(CacheUtil.getKeyWithMaxPair("age")); TimeUnit.SECONDS.sleep(2); System.out.println(CacheUtil.getKeyWithMaxPair("name")); // 查询不到了 System.out.println(CacheUtil.getKeyWithMaxPair("age")); } }
三、快取一致性
1. 常見方案
1.1 設定有效期限
- 給緩存設定有效期,到期後自動刪除。再次查詢時可以更新
- 優點:簡單,方便
- #缺點:時效性差,快取過期之前可能不一致
- 1.2 同步雙寫
- 在修改資料庫的同時,直接修改快取
- 優點:有程式碼侵入,快取與資料庫強一致性
- ##缺點:程式碼進入,耦合性高
- 場景:對一致性,失效性要求較高的快取資料
- 1.3 非同步通知
修改資料庫時發送事件通知,相關服務監聽到後修改快取資料
- 優勢:低耦合,可以同時通知多個快取服務
- 缺點:時效性一把,可能有快取不一致問題
- 場景:時效性一般,有多個服務需要同步
2. 基於Canal的非同步通知
- 基於資料庫增量日誌解析,提供增量資料訂閱和消費
- 基於mysql的主從備份的想法
- 2.1 mysql主從複製
#2.2 canal 工作原理
- MySQL master 收到dump 請求, 開始推送binary log 給slave (即canal )
- canal 解析binary log 物件(原始為byte 流)
#
以上是基於Java怎麼實作Redis多層緩存的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多態性、Lambda表達式、StreamsAPI、泛型和異常處理。 1.多態性讓不同類的對象可以作為共同基類的對象使用。 2.Lambda表達式使代碼更簡潔,特別適合處理集合和流。 3.StreamsAPI高效處理大數據集,支持聲明式操作。 4.泛型提供類型安全和重用性,編譯時捕獲類型錯誤。 5.異常處理幫助優雅處理錯誤,編寫可靠軟件。

java'stopfeatureSnificallyenhanceItsperformanCandScalability.1)對象 - 方向clincipleslike-polymormormormormormormormormormormormorableableflexibleandscalablecode.2)garbageCollectionAutectionAutoctionAutoctionAutoctionAutoctionAutoctionAutoMenateMememorymanateMmanateMmanateMmanagementButCancausElatemention.3)

JVM的核心組件包括ClassLoader、RuntimeDataArea和ExecutionEngine。 1)ClassLoader負責加載、鏈接和初始化類和接口。 2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。 3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector組成,負責bytecode的執行和優化。

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)對象 - 方向 - 方向上的allowslowsmodelowsmodelingreal-worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定結構,影響性能,安全性和便攜性。 1)theclassloaderloader,links andinitializesClasses.2)theexecutionEngineExecutionEngineExecutionEngineExecuteNexeCuteByteCuteByteCuteByTecuteByteCuteByteCuteBytecuteBytecuteByteCoDeinintolachineinstructionsions.3)Memo.3)Memo


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中