当前位置: 首页 > news >正文

缓存实战:Redis 与本地缓存

引言

在现代互联网应用中,缓存是提升系统性能和用户体验的关键技术之一。通过将频繁访问的数据存储在快速访问的存储介质中,可以显著减少对数据库的直接访问压力,从而提高系统的响应速度和吞吐量。

本文将从实战的角度出发,详细介绍如何使用 Redis 和本地缓存(如 Caffeine)来优化应用性能。我们将分别探讨 RedisTemplate 操作缓存、@Cacheable 方法缓存以及 Caffeine 本地缓存的使用场景和实现细节。


一、RedisTemplate 操作缓存

1. Redis 简介

Redis 是一个开源的高性能键值存储系统,支持多种数据结构(如字符串、哈希、列表、集合、有序集合等),广泛应用于缓存、消息队列、实时分析等领域。

2. 在 Spring Boot 中配置 Redis

首先,在 pom.xml 中添加 Redis 依赖:

<dependencies><dependency><groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>
</dependencies>

然后,在 application.properties 中配置 Redis 连接信息:

spring.redis.host=localhost  
spring.redis.port=6379  
spring.redis.password= 

 

3. 使用 RedisTemplate 进行基本操作

RedisTemplate 是 Spring Data Redis 提供的核心模板类,用于简化 Redis 的操作。

示例代码

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.stereotype.Service; @Service 
public class CacheService {@Autowired private RedisTemplate<String, Object> redisTemplate;public void setValue(String key, Object value) {redisTemplate.opsForValue().set(key,  value);}public Object getValue(String key) {return redisTemplate.opsForValue().get(key); }public void deleteKey(String key) {redisTemplate.delete(key); }
}

 

  • opsForValue():操作字符串类型的键值对。
  • set(key, value):设置键值对。
  • get(key):获取指定键的值。
  • delete(key):删除指定键。
4. 设置过期时间

为了避免缓存数据无限期占用内存,我们可以为键设置过期时间。

public void setValueWithExpire(String key, Object value, long expireSeconds) {redisTemplate.opsForValue().set(key,  value, expireSeconds);
}

 

  • expireSeconds:过期时间(单位:秒)。
5. 批量操作

RedisTemplate 还支持批量操作,以提高效率。

public void batchSetValue(Map<String, Object> entries) {redisTemplate.opsForValue().multiSet(entries); 
}public Map<String, Object> batchGetValue(Collection<String> keys) {return redisTemplate.opsForValue().multiGet(keys); 
}

 

二、@Cacheable 方法缓存

1. Spring Cache 简介

Spring Cache 是 Spring 提供的一套缓存抽象层,支持多种缓存实现(如 Redis、Caffeine、Ehcache 等)。@Cacheable 是 Spring Cache 中最常用的注解之一,用于标注需要缓存的方法。

2. 配置 Spring Cache

application.properties 中启用缓存:

spring.cache.type=redis  

 

3. 使用 @Cacheable 注解

示例代码:

import org.springframework.cache.annotation.Cacheable; 
import org.springframework.stereotype.Service; @Service 
public class UserService {@Cacheable(value = "users", key = "#id")public User getUserById(Long id) {// 从数据库查询用户 return userRepository.findById(id).orElse(null); }
}

 

  • value = "users":指定缓存的名称。
  • key = "#id":指定缓存的键,使用方法参数 id 的值。
4. 自定义缓存配置

可以通过 @CacheConfig 注解为类级别配置默认的缓存名称和键生成策略。

import org.springframework.cache.annotation.CacheConfig; 
import org.springframework.cache.annotation.Cacheable; 
import org.springframework.stereotype.Service; @Service 
@CacheConfig(cacheNames = "users")
public class UserService {@Cacheable(key = "#id")public User getUserById(Long id) {// 从数据库查询用户 return userRepository.findById(id).orElse(null); }
}

 

三、Caffeine 本地缓存

1. Caffeine 简介

Caffeine 是一个高性能的 Java 缓存库,由 Google 开发并维护。它支持本地缓存,并提供了丰富的功能(如自动过期、容量限制、统计信息等)。

2. 在 Spring Boot 中集成 Caffeine

首先,在 pom.xml 中添加 Caffeine 依赖:

<dependencies><dependency><groupId>com.github.benmanes</groupId> <artifactId>jcache</artifactId><version>1.0.0</version></dependency>
</dependencies>

 然后,在配置类中配置 Caffeine 缓存管理器:

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.cache.CacheManager; 
import org.springframework.cache.caffeine.CaffeineCacheManager; 
import com.github.benmanes.caffeine.jcache.JCache; @Configuration 
public class CacheConfig {@Bean public CacheManager cacheManager() {CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager("users");caffeineCacheManager.setCaffeine(JCache.Caffeine.newBuilder() .maximumSize(1000).expireAfterWrite(10, TimeUnit.MINUTES).build());return caffeineCacheManager;}
}

 

3. 使用 @Cacheable 结合 Caffeine

与 Redis 类似,我们可以使用 @Cacheable 注解结合 Caffeine 实现本地缓存。

import org.springframework.cache.annotation.Cacheable; 
import org.springframework.stereotype.Service; @Service 
public class UserService {@Cacheable(value = "users", key = "#id")public User getUserById(Long id) {// 从数据库查询用户 return userRepository.findById(id).orElse(null); }
}

四、总结与选择建议

1. 总结
  • Redis:适合分布式缓存场景,支持高并发和大数据量。
  • @Cacheable:简化缓存逻辑的实现,支持多种缓存后端。
  • Caffeine:适合本地缓存场景,性能优异且配置简单。
2. 选择建议
  • 如果需要分布式缓存且数据量较大,推荐使用 Redis。
  • 如果需要本地缓存且追求高性能,推荐使用 Caffeine。
  • 如果希望统一管理缓存逻辑,可以结合 @Cacheable 和具体的缓存实现(如 Redis 或 Caffeine)。

http://www.lryc.cn/news/534185.html

相关文章:

  • apisix的real-ip插件使用说明
  • 音视频协议
  • 第一财经对话东土科技 | 探索工业科技新边界
  • Maven 与企业项目的集成
  • 激活函数篇 01 —— 激活函数在神经网络的作用
  • 22.2、Apache安全分析与增强
  • Day.23
  • CentOS虚机在线扩容系统盘数据盘
  • 动手写ORM框架 - GeeORM第一天 database/sql 基础
  • 绘制中国平安股价的交互式 K 线图
  • [渗透测试]热门搜索引擎推荐— — shodan篇
  • JavaScript 在 VSCode 中的优势与应用
  • 深度学习之StyleGAN算法解析
  • 数据结构之排序
  • Vue.js 与第三方插件的集成
  • 基于Docker搭建ES集群,并设置冷热数据节点
  • MyBatis常见知识点
  • Redis --- 使用GEO实现经纬度距离计算
  • 【0403】Postgres内核 检查(procArray )给定 db 是否有其他 backend process 正在运行
  • [数据结构] Set的使用与注意事项
  • amis组件crud使用踩坑
  • 离线统信系统的python第三方库批量安装流程
  • 韶音科技:消费电子行业售后服务实现数字化转型,重塑客户服务体系
  • 神经网络|(九)概率论基础知识-泊松分布及python仿真
  • 114,【6】攻防世界 web wzsc_文件上传
  • 【Kubernetes的SpringCloud最佳实践】有Service是否还需要Eureka?
  • SQL最佳实践(笔记)
  • vue3学习四
  • C# LiteDB 使用教程
  • Python Pandas(3):DataFrame