基于SpringBoot的Redis开发实战教程

配置和集成缓存涉及多个步骤,从选择适当的缓存技术到实现缓存的存取操作。以下是具体的步骤和示例,假设我们使用Redis 作为缓存工具,并基于Spring Boot进行开发。

1. 选择和配置缓存技术

a. 选择缓存工具
  • Redis 是一个流行的内存数据结构存储工具,适用于各种缓存需求。
b. 添加依赖

在你的Spring Boot项目中,添加Redis相关的依赖。以下是使用Maven的示例:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
c. 配置Redis

application.propertiesapplication.yml 文件中配置Redis连接:

application.properties 示例:

properties 复制代码
spring.redis.host=localhost
spring.redis.port=6379

application.yml 示例:

yaml 复制代码
spring:
  redis:
    host: localhost
    port: 6379

2. 配置Spring Boot集成Redis

a. 创建Redis配置类

创建一个Redis配置类,配置RedisTemplate和相关的序列化设置:

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
        return template;
    }
    
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory();
    }
}
b. 使用RedisTemplate进行缓存操作

创建服务类来实现缓存操作,包括缓存的存取:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CachedProductService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String PRODUCT_KEY_PREFIX = "product:";

    public Product getProduct(Long id) {
        String key = PRODUCT_KEY_PREFIX + id;
        Product product = (Product) redisTemplate.opsForValue().get(key);
        if (product == null) {
            // Cache miss: retrieve data from the database
            product = fetchProductFromDatabase(id);
            // Store data in the cache
            redisTemplate.opsForValue().set(key, product, 1, TimeUnit.HOURS);
        }
        return product;
    }

    public void addProduct(Product product) {
        // Save product to the database
        saveProductToDatabase(product);
        // Invalidate cache
        redisTemplate.delete(PRODUCT_KEY_PREFIX + product.getId());
    }

    public void updateProduct(Product product) {
        // Update product in the database
        updateProductInDatabase(product);
        // Update cache
        redisTemplate.opsForValue().set(PRODUCT_KEY_PREFIX + product.getId(), product, 1, TimeUnit.HOURS);
    }

    public void deleteProduct(Long id) {
        // Delete product from the database
        deleteProductFromDatabase(id);
        // Remove from cache
        redisTemplate.delete(PRODUCT_KEY_PREFIX + id);
    }

    private Product fetchProductFromDatabase(Long id) {
        // Implement database fetch logic
        return new Product(); // Placeholder
    }

    private void saveProductToDatabase(Product product) {
        // Implement database save logic
    }

    private void updateProductInDatabase(Product product) {
        // Implement database update logic
    }

    private void deleteProductFromDatabase(Long id) {
        // Implement database delete logic
    }
}

3. 实现缓存操作

a. 存取缓存
  • 存取数据 :使用 redisTemplate.opsForValue().get(key) 从缓存中读取数据,使用 redisTemplate.opsForValue().set(key, value, timeout, unit) 将数据存入缓存。
b. 缓存失效
  • 过期时间:在将数据存入缓存时设置过期时间,以避免缓存数据过期。
c. 缓存更新和删除
  • 更新缓存:在数据更新或删除时,确保缓存中的数据也被相应更新或删除。

4. 测试和优化

a. 测试
  • 单元测试:编写测试用例,验证缓存操作是否正常工作。

    java 复制代码
    @SpringBootTest
    public class CachedProductServiceTests {
    
        @Autowired
        private CachedProductService cachedProductService;
    
        @Test
        public void testGetProduct() {
            Product product = cachedProductService.getProduct(1L);
            assertNotNull(product);
        }
        
        @Test
        public void testAddProduct() {
            Product product = new Product();
            cachedProductService.addProduct(product);
            // Verify product addition logic
        }
        
        @Test
        public void testUpdateProduct() {
            Product product = new Product();
            cachedProductService.updateProduct(product);
            // Verify product update logic
        }
        
        @Test
        public void testDeleteProduct() {
            cachedProductService.deleteProduct(1L);
            // Verify product deletion logic
        }
    }
b. 优化
  • 缓存配置:根据实际使用情况调整缓存大小、过期时间等配置。
  • 监控和分析:监控缓存命中率和性能,进行优化。

通过以上步骤,你可以成功配置和集成缓存,并定义缓存操作。这将显著提升数据服务的性能和响应速度,同时减轻数据库的负担。

相关推荐
QQ1__8115175154 小时前
Spring boot名城小区物业管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
直奔標竿6 小时前
Java开发者AI转型第二十七课!Spring AI 个人知识库实战(六)——全栈闭环收官,解锁前端流式渲染终极技巧
java·开发语言·前端·人工智能·后端·spring
虹科网络安全7 小时前
艾体宝产品|深度解读 Redis 8.4 新增功能:原子化 Slot 迁移(上)
数据库·redis·bootstrap
yoyo_zzm9 小时前
Laravel6.x新特性全解析
java·spring boot·后端
源码宝10 小时前
基于 SpringBoot + Vue 的医院随访系统:技术架构与功能实现
java·vue.js·spring boot·架构·源码·随访系统·随访管理
虹科网络安全11 小时前
艾体宝新闻|Redis 月度更新速览:2026 年 3 月
数据库·redis·缓存
空中海11 小时前
Spring Cloud 专家级面试题库
spring·spring cloud·面试
空中海11 小时前
Spring Boot 专家级面试题库
spring boot·后端·面试
y = xⁿ12 小时前
Redis八股学习日记:布隆过滤器
数据库·redis·学习
空中海12 小时前
第二篇:注册中心篇 — Nacos 与 Eureka 服务注册发现
spring boot·云原生·eureka