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

Redis与Caffeine的结合使用详解(高效的二级缓存解决方案)

目录

    • 一、Redis与Caffeine的结合使用
      • (一)引入依赖
      • (二)配置缓存
      • (三)配置 Caffeine 缓存
      • (四)配置 Redis 缓存
      • (五)使用缓存
    • 二、总结

一、Redis与Caffeine的结合使用

Redis 和 Caffeine 是两种广受欢迎的缓存技术,Redis 是一个高性能的键值数据库,提供了数据持久化和分布式缓存功能;Caffeine 是一个高性能的缓存库,访问速度快,能够提供接近内存的访问效率。将 Redis 和 Caffeine 结合起来,可以构建一个高效的二级缓存解决方案。Caffeine 作为一级缓存,提供快速访问,而 Redis 作为二级缓存,解决数据共享和持久化问题。

(一)引入依赖

pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.8.1</version>
</dependency>

(二)配置缓存

application.yml 中配置 Redis 的连接信息:

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 0
    timeout: 10000ms
    lettuce:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0

(三)配置 Caffeine 缓存

import com.github.ben.manes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CaffeineConfig {
    @Bean
    public CacheManager caffeineCacheManager() {
        return new CaffeineCacheManager(
            Caffeine.newBuilder()
                .initialCapacity(128)
                .maximumSize(1024)
                .expireAfterWrite(60, TimeUnit.SECONDS)
                .build()
        );
    }
}

(四)配置 Redis 缓存

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

(五)使用缓存

在业务代码中,可以使用 @Cacheable@CachePut@CacheEvict 注解来简化缓存操作。

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    @Cacheable(cacheNames = "order", key = "#id")
    public Order getOrderById(Long id) {
        // 查询数据库
        return orderMapper.selectById(id);
    }

    @CachePut(cacheNames = "order", key = "#order.id")
    public Order updateOrder(Order order) {
        // 更新数据库
        orderMapper.updateById(order);
        // 更新 Redis
        redisTemplate.opsForValue().set("order:" + order.getId(), order, 120, TimeUnit.SECONDS);
        return order;
    }

    @CacheEvict(cacheNames = "order", key = "#id")
    public void deleteOrder(Long id) {
        // 删除数据库记录
        orderMapper.deleteById(id);
        // 删除 Redis 缓存
        redisTemplate.delete("order:" + id);
    }
}

二、总结

通过结合 Redis 和 Caffeine,可以构建一个高效的二级缓存解决方案。Caffeine 作为一级缓存,提供快速的本地访问;Redis 作为二级缓存,提供数据的持久化和分布式共享。这种架构在提高数据访问速度、减少数据库压力方面具有显著优势。希望本文的示例和讲解对您有所帮助,如果您在实现二级缓存时有任何疑问,欢迎随时交流探讨!

相关文章:

  • 条件变量condition_variable
  • elementui table禁用全选,一次限制勾选一项。
  • vector的应用
  • Webpack中的文件指纹:给资源戴上个“名牌”
  • OpenCV 图形API(23)图像和通道合成
  • 组合模式计算多项式
  • 【MYSQL从入门到精通】数据库基础操作、数据类型
  • 数据结构 -- 图的遍历
  • 文件操作和IO - 2
  • Model Context Protocol(MCP)模型上下文协议
  • spark core编程之行动算子、累加器、广播变量
  • 在51单片机上实现平滑呼吸灯:50us定时器PWM实战指南
  • Shell脚本提交Spark任务简单案例
  • Java基础 4.12
  • 《jQuery EasyUI 插件》
  • Linux基础5
  • 【数据结构与算法】ArrayList 和 顺序表
  • Python进阶(3):函数(接上篇)
  • Linux基础8
  • Linux磁盘大师:存储管理完全指南
  • 当当网电子商务网站建设特点/湖南seo优化价格
  • 可以做片头的网站/成都网站建设技术支持
  • 中标查询/青岛seo招聘
  • 学网站建设需要什么/竞价推广教程
  • 做网站的商标是哪类/优化大师win7官方免费下载
  • 网站怎么弄二维码/搜索引擎优化的简称是