自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

有Redis為什么還要本地緩存?談?wù)勀銓Ρ镜鼐彺娴睦斫猓?/h1>

數(shù)據(jù)庫 Redis
生產(chǎn)環(huán)境通常會使用本地緩存 + Redis 緩存,一起實(shí)現(xiàn)多級緩存,以提升程序的運(yùn)行效率,而本地緩存的常見實(shí)現(xiàn)有 Ehcache、Caffeine、Guava Cache 等。

本地緩存是將數(shù)據(jù)存儲在應(yīng)用程序所在的本地內(nèi)存中的緩存方式。既然,已經(jīng)有了 Redis 可以實(shí)現(xiàn)分布式緩存了,為什么還需要本地緩存呢?接下來,我們一起來看。

為什么需要本地緩存?

盡管已經(jīng)有 Redis 緩存了,但本地緩存也是非常有必要的,因?yàn)樗幸韵聝?yōu)點(diǎn):

  1. 速度優(yōu)勢:本地緩存直接利用本地內(nèi)存,訪問速度非???,能夠顯著降低數(shù)據(jù)訪問延遲。
  2. 減少網(wǎng)絡(luò)開銷:使用本地緩存可以減少與遠(yuǎn)程緩存(如 Redis)之間的數(shù)據(jù)交互,從而降低網(wǎng)絡(luò) I/O 開銷。
  3. 降低服務(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)有以下幾種:

  1. Ehcache
  2. Caffeine
  3. 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 是用于緩存管理的注解,它們的含義如下:

  1. @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);
}
  1. @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;
}
  1. @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ù)一致性問題要如何保證呢?

責(zé)任編輯:武曉燕 來源: 磊哥和Java
相關(guān)推薦

2023-11-11 19:43:12

緩存數(shù)據(jù)庫

2022-06-08 08:45:46

Redis緩存代碼

2023-05-12 11:52:21

緩存場景性能

2019-11-20 10:39:35

iPhone緩存清理

2024-04-24 10:24:09

2012-05-16 16:06:25

VMwareSSDvSphere 5

2011-09-01 10:27:26

Android圖片本地緩存Android遠(yuǎn)程圖片

2013-07-03 15:11:41

ANdroid

2015-02-02 10:03:50

2019-08-16 10:54:03

本地存儲javascripthttp緩存

2024-12-06 10:02:46

2023-03-10 13:33:00

緩存穿透緩存擊穿緩存雪崩

2019-10-12 14:19:05

Redis數(shù)據(jù)庫緩存

2022-06-07 08:39:35

RPCHTTP

2018-11-30 09:00:19

html5cssjavascript

2011-07-25 17:20:51

組策略本地組策略

2011-02-18 09:34:10

SQLite

2012-02-01 14:12:55

iOS本地緩存機(jī)制

2021-02-17 21:04:03

Ehcache緩存Java

2022-06-30 09:10:33

NoSQLHBaseRedis
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號