百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

有Redis为什么还要本地缓存?谈谈你对本地缓存的理解?

nanshan 2024-12-12 14:06 12 浏览 0 评论

本地缓存是将数据存储在应用程序所在的本地内存中的缓存方式。既然,已经有了 Redis 可以实现分布式缓存了,为什么还需要本地缓存呢?接下来,我们一起来看。

为什么需要本地缓存?

尽管已经有 Redis 缓存了,但本地缓存也是非常有必要的,因为它有以下优点:

  1. 速度优势:本地缓存直接利用本地内存,访问速度非常快,能够显著降低数据访问延迟。
  2. 减少网络开销:使用本地缓存可以减少与远程缓存(如 Redis)之间的数据交互,从而降低网络 I/O 开销。
  3. 降低服务器压力:本地缓存能够分担服务器的数据访问压力,提高系统的整体稳定性。

因此,在生产环境中,我们通常使用本地缓存+Redis 缓存一起组合成多级缓存,来共同保证程序的运行效率

多级缓存

多级缓存是一种缓存架构策略,它使用多个层次的缓存来存储数据,以提高数据访问速度和系统性能,最简单的多级缓存就是由本地缓存 + Redis 分布式缓存组成的,如图所示:


多级缓存在获取时的实现代码如下:

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 中的数据放入本地缓存
        cacheManager.getCache("localCache").put(key, redisValue);
        return redisValue;
    }
    return null;
}

本地缓存的实现

本地缓存常见的方式实现有以下几种:

  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 目录下创建 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 应用的主类或配置类上添加 @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 使用缓存

创建一个服务类并使用 @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 应用的主类或配置类上添加 @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 缓存

创建一个配置类来配置 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 使用缓存

创建一个服务类并使用 @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 应用的主类或配置类上添加 @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 缓存

创建一个配置类来配置 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 使用缓存

创建一个服务类并使用 @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;
    }
}

知识扩展:@Cacheable、@CachePut、@CacheEvict

在 Spring 框架中,@Cacheable、@CachePut 和 @CacheEvict 是用于缓存管理的注解,它们的含义如下:

  1. @Cacheable:用于声明一个方法的返回值是可以被缓存的。当方法被调用时,Spring Cache 会先检查缓存中是否存在相应的数据。如果存在,则直接返回缓存中的数据,避免重复执行方法;如果不存在,则执行方法并将返回值存入缓存中。它的使用示例如下:
@Cacheable(value = "users", key = "#id")
public User getUserById(String id) {
// 模拟从数据库中获取用户信息
System.out.println("Fetching user from database: " + id);
return new User(id, "User Name " + id);
}
  1. @CachePut:用于更新缓存中的数据。与 @Cacheable 不同,@CachePut 注解的方法总是会执行,并将返回值更新到缓存中。无论缓存中是否存在相应的数据,该方法都会执行,并将新的数据存入缓存中(如果缓存中已存在数据,则覆盖它)。它的使用示例如下:
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
// 模拟更新数据库中的用户信息
System.out.println("Updating user in database: " + user.getId());
// 假设更新成功
return user;
}
  1. @CacheEvict:用于删除缓存中的数据。当方法被调用时,指定的缓存项将被删除。这可以用于清除旧数据或使缓存项失效。它的使用示例如下:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(String id) {
// 模拟从数据库中删除用户信息
System.out.println("Deleting user from database: " + id);
}
// 清除整个缓存,而不仅仅是特定的条目
@CacheEvict(value = "users", allEntries = true)
public void clearAllUsersCache() {
    System.out.println("Clearing all users cache");
}

小结

生产环境通常会使用本地缓存 + Redis 缓存,一起实现多级缓存,以提升程序的运行效率,而本地缓存的常见实现有 Ehcache、Caffeine、Guava Cache 等。然而,凡事有利就有弊,那么多级缓存最大的问题就是数据一致性问题,对于多级缓存的数据一致性问题要如何保证呢?

本文已收录到我的面试小站 [www.javacn.site](https://www.javacn.site),其中包含的内容有:并发编程、MySQL、Redis、Spring、Spring MVC、Spring Boot、Spring Cloud、MyBatis、JVM、设计模式、消息队列等模块。

相关推荐

Let’s Encrypt免费搭建HTTPS网站

HTTPS(全称:HyperTextTransferProtocoloverSecureSocketLayer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版。即HTTP下加入...

使用Nginx配置TCP负载均衡(nginx tcp负载)

假设Kubernetes集群已经配置好,我们将基于CentOS为Nginx创建一个虚拟机。以下是实验种设置的详细信息:Nginx(CenOS8Minimal)-192.168.1.50Kube...

Nginx负载均衡及支持HTTPS与申请免费SSL证书

背景有两台minio文件服务器已做好集群配置,一台是192.168.56.41:9000;另一台是192.168.56.42:9000。应用程序通过Nginx负载均衡调用这两台minio服务,减轻单点...

HTTPS配置实战(https配置文件)

原因现在网站使用HTTPS是规范操作之一,前些日子买了腾讯云服务,同时申请了域名http://www.asap2me.top/,目前该域名只支持HTTP,想升级为HTTPS。关于HTTPS的链接过程大...

只有IP地址没有域名实现HTTPS访问方法

一般来说,要实现HTTPS,得有个注册好的域名才行。但有时候呢,咱只有服务器的IP地址,没注册域名,这种特殊情况下,也能照样实现HTTPS安全访问,按下面这些步骤来就行:第一步,先确认公网...

超详解:HTTPS及配置Django+HTTPS开发环境

众所周知HTTP协议是以TCP协议为基石诞生的一个用于传输Web内容的一个网络协议,在“网络分层模型”中属于“应用层协议”的一种。在这里我们并不研究该协议标准本身,而是从安全角度去探究使用该协议传输数...

Godaddy购买SSL之后Nginx配置流程以及各种错误的解决

完整流程:参考地址:https://sg.godaddy.com/zh/help/nginx-generate-csrs-certificate-signing-requests-3601生成NGI...

Nginx从安装到高可用,一篇搞定(nginx安装与配置详解)

一、Nginx安装1、去官网http://nginx.org/下载对应的nginx包,推荐使用稳定版本2、上传nginx到linux系统3、安装依赖环境(1)安装gcc环境yuminstallgc...

阿里云免费证书申请,配置安装,使用tomcat,支持http/https访问

参数说明商品类型默认已选择云盾证书服务(无需修改)。云盾证书服务类型SSL证书服务的类型。默认已选择云盾SSL证书(无需修改),表示付费版SSL证书。如果您需要免费领取或付费扩容DV单域名证书【免费试...

你试过两步实现Nginx的规范配置吗?极速生成Nginx配置小工具

NGINX是一款轻量级的Web服务器,最强大的功能之一是能够有效地提供HTML和媒体文件等静态内容。NGINX使用异步事件驱动模型,在负载下提供可预测的性能。是当下最受欢迎的高性能的Web...

从零开始搭建HTTPS服务(搭建https网站)

搭建HTTPS服务的最初目的是为了开发微信小程序,因为wx.request只允许发起HTTPS请求,并且还必须和指定的域名进行网络通信。要从零开始搭建一个HTTPS的服务需要下面4...

群晖NAS使用官网域名和自己的域名配置SSL实现HTTPS访问

安全第一步,群晖NAS使用官网域名和自己的域名配置SSL实现HTTPS访问【新手导向】NAS本质还是一个可以随时随地访问的个人数据存储中心,我们在外网访问的时候,特别是在公网IP下,其实会面临着很多安...

让网站快速升级HTTPS协议提高安全性

为什么用HTTPS网络安全越来越受到重视,很多互联网服务网站,都已经升级改造为https协议。https协议下数据包是ssl/tcl加密的,而http包是明文传输。如果请求一旦被拦截,数据就会泄露产生...

用Https方式访问Harbor-1.9版本(https访问流程)

我上周在头条号写过一篇原创文章《Docker-Harbor&Docker-kitematic史上最详细双系统配置手册》,这篇算是它的姊妹篇吧。这篇文章也将用到我在头条写的另一篇原创文章的...

如何启用 HTTPS 并配置免费的 SSL 证书

在Linux服务器上启用HTTPS并配置免费的SSL证书(以Let'sEncrypt为例)可以通过以下步骤完成:---###**一、准备工作**1.**确保域名已解析**...

取消回复欢迎 发表评论: