有Redis為什么還要本地緩存?談?wù)勀銓Ρ镜鼐彺娴睦斫猓?/h1>
本地緩存是將數(shù)據(jù)存儲在應(yīng)用程序所在的本地內(nèi)存中的緩存方式。既然,已經(jīng)有了 Redis 可以實(shí)現(xiàn)分布式緩存了,為什么還需要本地緩存呢?接下來,我們一起來看。
為什么需要本地緩存?
盡管已經(jīng)有 Redis 緩存了,但本地緩存也是非常有必要的,因?yàn)樗幸韵聝?yōu)點(diǎn):
- 速度優(yōu)勢:本地緩存直接利用本地內(nèi)存,訪問速度非???,能夠顯著降低數(shù)據(jù)訪問延遲。
- 減少網(wǎng)絡(luò)開銷:使用本地緩存可以減少與遠(yuǎn)程緩存(如 Redis)之間的數(shù)據(jù)交互,從而降低網(wǎng)絡(luò) I/O 開銷。
- 降低服務(wù)器壓力:本地緩存能夠分擔(dān)服務(wù)器的數(shù)據(jù)訪問壓力,提高系統(tǒng)的整體穩(wěn)定性。
因此,在生產(chǎn)環(huán)境中,我們通常使用本地緩存+Redis 緩存一起組合成多級緩存,來共同保證程序的運(yùn)行效率。
多級緩存
多級緩存是一種緩存架構(gòu)策略,它使用多個層次的緩存來存儲數(shù)據(jù),以提高數(shù)據(jù)訪問速度和系統(tǒng)性能,最簡單的多級緩存就是由本地緩存 + Redis 分布式緩存組成的,如圖所示:
圖片
多級緩存在獲取時的實(shí)現(xiàn)代碼如下:
public Object getFromCache(String key) {
// 先從本地緩存中查找
Cache.ValueWrapper localCacheValue = cacheManager.getCache("localCache").get(key);
if (localCacheValue!= null) {
return localCacheValue.get();
}
// 如果本地緩存未命中,從 Redis 中查找
Object redisValue = redisTemplate.opsForValue().get(key);
if (redisValue!= null) {
// 將 Redis 中的數(shù)據(jù)放入本地緩存
cacheManager.getCache("localCache").put(key, redisValue);
return redisValue;
}
return null;
}
本地緩存的實(shí)現(xiàn)
本地緩存常見的方式實(shí)現(xiàn)有以下幾種:
- Ehcache
- Caffeine
- Guava Cache
它們的基本使用如下。
1.Ehcache
1.1 添加依賴
在 pom.xml 文件中添加 Ehcache 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
1.2 配置 Ehcache
在 src/main/resources 目錄下創(chuàng)建 ehcache.xml 文件:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd">
<cache name="myCache"
maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"/>
</ehcache>
1.3 啟用緩存
在 Spring Boot 應(yīng)用的主類或配置類上添加 @EnableCaching 注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
1.4 使用緩存
創(chuàng)建一個服務(wù)類并使用 @Cacheable 注解:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Cacheable(value = "myCache", key = "#id")
public String getData(String id) {
// 模擬耗時操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Data for " + id;
}
}
2.Caffeine
2.1 添加依賴
在 pom.xml 文件中添加 Caffeine 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
2.2 啟用緩存
在 Spring Boot 應(yīng)用的主類或配置類上添加 @EnableCaching 注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
2.3 配置 Caffeine 緩存
創(chuàng)建一個配置類來配置 Caffeine 緩存:
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager("myCache");
cacheManager.setCaffeine(Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(120, TimeUnit.SECONDS));
return cacheManager;
}
}
2.4 使用緩存
創(chuàng)建一個服務(wù)類并使用 @Cacheable 注解:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Cacheable(value = "myCache", key = "#id")
public String getData(String id) {
// 模擬耗時操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Data for " + id;
}
}
3.Guava Cache
3.1 添加依賴
在 pom.xml 文件中添加 Guava 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
3.2 啟用緩存
在 Spring Boot 應(yīng)用的主類或配置類上添加 @EnableCaching 注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
3.3 配置 Guava 緩存
創(chuàng)建一個配置類來配置 Guava 緩存:
import com.google.common.cache.CacheBuilder;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {
@Override
protected Cache createConcurrentMapCache(String name) {
return new ConcurrentMapCache(name,
CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(120, TimeUnit.SECONDS)
.build().asMap(), false);
}
};
return cacheManager;
}
}
3.4 使用緩存
創(chuàng)建一個服務(wù)類并使用 @Cacheable 注解:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Cacheable(value = "myCache", key = "#id")
public String getData(String id) {
// 模擬耗時操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Data for " + id;
}
}
知識擴(kuò)展:@Cacheable、@CachePut、@CacheEvict
在 Spring 框架中,@Cacheable、@CachePut 和 @CacheEvict 是用于緩存管理的注解,它們的含義如下:
- @Cacheable:用于聲明一個方法的返回值是可以被緩存的。當(dāng)方法被調(diào)用時,Spring Cache 會先檢查緩存中是否存在相應(yīng)的數(shù)據(jù)。如果存在,則直接返回緩存中的數(shù)據(jù),避免重復(fù)執(zhí)行方法;如果不存在,則執(zhí)行方法并將返回值存入緩存中。它的使用示例如下:
@Cacheable(value = "users", key = "#id")
public User getUserById(String id) {
// 模擬從數(shù)據(jù)庫中獲取用戶信息
System.out.println("Fetching user from database: " + id);
return new User(id, "User Name " + id);
}
- @CachePut:用于更新緩存中的數(shù)據(jù)。與 @Cacheable 不同,@CachePut 注解的方法總是會執(zhí)行,并將返回值更新到緩存中。無論緩存中是否存在相應(yīng)的數(shù)據(jù),該方法都會執(zhí)行,并將新的數(shù)據(jù)存入緩存中(如果緩存中已存在數(shù)據(jù),則覆蓋它)。它的使用示例如下:
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
// 模擬更新數(shù)據(jù)庫中的用戶信息
System.out.println("Updating user in database: " + user.getId());
// 假設(shè)更新成功
return user;
}
- @CacheEvict:用于刪除緩存中的數(shù)據(jù)。當(dāng)方法被調(diào)用時,指定的緩存項(xiàng)將被刪除。這可以用于清除舊數(shù)據(jù)或使緩存項(xiàng)失效。它的使用示例如下:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(String id) {
// 模擬從數(shù)據(jù)庫中刪除用戶信息
System.out.println("Deleting user from database: " + id);
}
// 清除整個緩存,而不僅僅是特定的條目
@CacheEvict(value = "users", allEntries = true)
public void clearAllUsersCache() {
System.out.println("Clearing all users cache");
}
小結(jié)
生產(chǎn)環(huán)境通常會使用本地緩存 + Redis 緩存,一起實(shí)現(xiàn)多級緩存,以提升程序的運(yùn)行效率,而本地緩存的常見實(shí)現(xiàn)有 Ehcache、Caffeine、Guava Cache 等。然而,凡事有利就有弊,那么多級緩存最大的問題就是數(shù)據(jù)一致性問題,對于多級緩存的數(shù)據(jù)一致性問題要如何保證呢?