有Redis为什么还要本地缓存?谈谈你对本地缓存的理解?
nanshan 2024-12-12 14:06 13 浏览 0 评论
本地缓存是将数据存储在应用程序所在的本地内存中的缓存方式。既然,已经有了 Redis 可以实现分布式缓存了,为什么还需要本地缓存呢?接下来,我们一起来看。
为什么需要本地缓存?
尽管已经有 Redis 缓存了,但本地缓存也是非常有必要的,因为它有以下优点:
- 速度优势:本地缓存直接利用本地内存,访问速度非常快,能够显著降低数据访问延迟。
- 减少网络开销:使用本地缓存可以减少与远程缓存(如 Redis)之间的数据交互,从而降低网络 I/O 开销。
- 降低服务器压力:本地缓存能够分担服务器的数据访问压力,提高系统的整体稳定性。
因此,在生产环境中,我们通常使用本地缓存+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;
}
本地缓存的实现
本地缓存常见的方式实现有以下几种:
- 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 目录下创建 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 是用于缓存管理的注解,它们的含义如下:
- @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);
}
- @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;
}
- @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、设计模式、消息队列等模块。
相关推荐
- 服务器温度监控--lm-sensors(服务器温度怎么看)
-
lm-sensors是一款linux的硬件监控的软件,可以帮助我们来监控主板,CPU的工作电压,风扇转速、温度等数据。这些数据我们通常在主板的BIOS也可以看到。当我们可以在机器运行的时候通过...
- MySQL版本区别及管理(mysql版本最新版本)
-
MySQL版本区别及管理一.MySQL5.6与MySQL5.7安装的区别1、cmake的时候加入了bostorg2、初始化时使用mysqld--initialize替代mysql_install...
- Linux技术问答系列-NO4(linux必知必会)
-
一.绝对路径用什么符号表示?当前目录、上层目录用什么表示?主目录用什么表示?切换目录用什么命令?绝对路径:如/etc/init.d当前目录和上层目录:./../主目录:~/切换目录:cd二...
- 猫盘原版系统开启ssh教程(猫盘原版系统怎么样)
-
猫盘是之前网上流传许久的矿渣,默认其系统不支持SSH功能,为了能打开其SSH功能,我特意制作操作教程如下:1、到网盘下载相关软件,利用猫盘系统自带功能,将assets放入个人存储目录下,并牢记对应的...
- 一探究竟——天融信网闸TopRules7000
-
网闸即:安全隔离与信息交换系统,常用作企业内外网隔离与业务互访用途。相比给服务器加多块网卡跨多个网段来说,网闸提供了更加安全的方式。探究背景:某次,网闸配置新业务,重启设备查看是否生效,结果发现刚重启...
- 操作系统加固通用Linux篇(linux系统加固常见操作)
-
1检查是否配置登陆超时时间设置编辑vi/etc/profile文件,配置TMOUT将值设置为低于300.TMOUT=3002检查是否禁止root用户登录FTP设置如下将对应配置文件中,设置roo...
- zabbix agent的安装与配置(zabbix-agent安装)
-
Agent安装rpm-ivhzabbix-agent-3.2.4-1.el6.x86_64.rpm安装完成后,zabbixagent端已经安装完成了,zabbixagent端的配置目录位于/e...
- Linux基础命令之计划任务(linux计划任务crontab)
-
一、计划任务1、at只能执行一次语法:at时间服务:atd必须开启123[root@xuegod163~]#/etc/init.d/atdstatus#查看服务状态atd(pid2...
- Secure Delivery Center (SDC)安装指南二:Delivery Hub
-
免费下载SecureDeliveryCenter2015>7月23日软件分发管理神器SecureDeliveryCenter免费技术交流会,MyEclipse原厂商倾力主讲,敬请关注!...
- OpenWrt 常用命令及用法!!(openwrt常用功能)
-
OpenWrt是一个高度可定制的嵌入式Linux操作系统,常用于路由器等网络设备。以下是一些常见的OpenWrt命令及其详细解释和示例操作:一、系统信息相关命令1.`uname-a``u...
- Linux 设置定时任务crontab命令(linux定时任务cron表达式)
-
看了同事的脚本,发现他用了cron来自检自身的那个程序是否崩溃了,这是有多大的不自信才用这种机制的?点击(此处)折叠或打开$sudocat/var/spool/cron/crontabs/ro...
- vCenter纳管ESXI主机出错(vsphere esxi)
-
vCenter纳管主机的大致步骤为:(1)vc和esxi交换证书,确立信任;(2)esxi把自己的资源信息同步到VC,VC建立清单。(3)VC在esxi建立几个操作用户;(4)然后下发...
- 从选购到安装 小白也能看懂的超全NAS经验分享
-
0.篇首语Hello大家好,我是KC,上一篇器材和工作流分享的文章里,有小伙伴问我怎么没有提到NAS?其实是因为前段时间碰巧更换了一台新NAS,折腾了一段时间很多内容还没来及整理和汇总,今天就...
- 手把手教你!如何在 Linux 服务器中搭建 Sentinel 环境?
-
你在Linux服务器上搭建Sentinel环境时,是不是也遇到过各种报错,要么是启动失败,要么是配置后无法正常访问控制台?看着同事顺利搭建好,自己却一头雾水,别提多着急了!其实,很多互联网大厂...
- 服务器被暴力破解的解决办法(二)(服务器被攻破严重吗)
-
上一次,我们说到小王公司服务器遭遇暴力破解,拿到解决方案回公司就开始部署。部署完成后的确起到了一定的效果,不过接下来的一个问题让他很头疼,原来黑客虽然攻入不进系统,但是依旧不依不饶的进行暴力破解。...
你 发表评论:
欢迎- 一周热门
-
-
极空间如何无损移机,新Z4 Pro又有哪些升级?极空间Z4 Pro深度体验
-
UOS服务器操作系统防火墙设置(uos20关闭防火墙)
-
如何修复用户配置文件服务在 WINDOWS 上登录失败的问题
-
手机如何设置与显示准确时间的详细指南
-
如何在安装前及安装后修改黑群晖的Mac地址和Sn系列号
-
日本海上自卫队的军衔制度(日本海上自卫队的军衔制度是什么)
-
爱折腾的特斯拉车主必看!手把手教你TESLAMATE的备份和恢复
-
10个免费文件中转服务站,分享文件简单方便,你知道几个?
-
FANUC 0i-TF数据备份方法(fanuc系统备份教程)
-
NAS:DS video/DS file/DS photo等群晖移动端APP远程访问的教程
-
- 最近发表
-
- 服务器温度监控--lm-sensors(服务器温度怎么看)
- MySQL版本区别及管理(mysql版本最新版本)
- Linux技术问答系列-NO4(linux必知必会)
- 猫盘原版系统开启ssh教程(猫盘原版系统怎么样)
- 一探究竟——天融信网闸TopRules7000
- 操作系统加固通用Linux篇(linux系统加固常见操作)
- zabbix agent的安装与配置(zabbix-agent安装)
- Linux基础命令之计划任务(linux计划任务crontab)
- Secure Delivery Center (SDC)安装指南二:Delivery Hub
- OpenWrt 常用命令及用法!!(openwrt常用功能)
- 标签列表
-
- linux 查询端口号 (58)
- docker映射容器目录到宿主机 (66)
- 杀端口 (60)
- yum更换阿里源 (62)
- internet explorer 增强的安全配置已启用 (65)
- linux自动挂载 (56)
- 禁用selinux (55)
- sysv-rc-conf (69)
- ubuntu防火墙状态查看 (64)
- windows server 2022激活密钥 (56)
- 无法与服务器建立安全连接是什么意思 (74)
- 443/80端口被占用怎么解决 (56)
- ping无法访问目标主机怎么解决 (58)
- fdatasync (59)
- 405 not allowed (56)
- 免备案虚拟主机zxhost (55)
- linux根据pid查看进程 (60)
- dhcp工具 (62)
- mysql 1045 (57)
- 宝塔远程工具 (56)
- ssh服务器拒绝了密码 请再试一次 (56)
- ubuntu卸载docker (56)
- linux查看nginx状态 (63)
- tomcat 乱码 (76)
- 2008r2激活序列号 (65)