在 Spring 中使用 Redis 进行缓存

38 篇文章 0 订阅

Redis 是一个高性能的内存数据库,常用于缓存以提升应用的响应速度和性能。Spring 提供了对 Redis 缓存的良好支持,本文将介绍如何在 Spring 应用中集成和使用 Redis 进行缓存。

1. 引入 Redis 依赖

首先,在项目的 pom.xml 文件中添加 Spring Data Redis 和 Spring Cache 的依赖:

<dependencies>
    <!-- Spring 缓存依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    
    <!-- Spring Data Redis 依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    <!-- Jedis 客户端依赖 -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
</dependencies>

2. 配置 Redis

application.properties 文件中添加 Redis 的配置:

spring.redis.host=localhost
spring.redis.port=6379
spring.cache.type=redis

3. Spring 缓存配置

在 Spring 应用中启用缓存,并配置 Redis 作为缓存管理器。在主配置类中添加以下内容:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(10))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(config)
                .build();
    }

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

4. 使用缓存

在需要缓存的方法上使用 @Cacheable 注解:

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

@Service
public class UserService {

    @Cacheable(value = "users", key = "#userId")
    public String getUserById(String userId) {
        // 模拟耗时操作,例如数据库查询
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "User:" + userId;
    }
}

在上述代码中,getUserById 方法将会被缓存,当使用相同的参数调用时,将直接返回缓存中的结果,而不会再次执行方法体。

5. 清除缓存

可以使用 @CacheEvict 注解清除缓存:

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

@Service
public class UserService {

    @CacheEvict(cacheNames = "users", allEntries = true)
    public void clearCache() {
        // 清除缓存
    }
}

6. 测试缓存

编写测试代码来验证缓存功能:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CacheTestRunner implements CommandLineRunner {

    @Autowired
    private UserService userService;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("First call: " + userService.getUserById("1"));
        System.out.println("Second call: " + userService.getUserById("1"));
        System.out.println("Third call: " + userService.getUserById("2"));
    }
}

运行应用,你将会看到第一次调用 getUserById 方法时有 3 秒的延迟,而后续调用相同参数的方法将会立即返回结果。

结论

通过本文的介绍,我们了解了如何在 Spring 中集成和使用 Redis 进行缓存。通过配置 Redis 和使用 Spring 提供的缓存注解,可以显著提升应用的性能。Redis 的高性能和 Spring 的灵活性结合,使得缓存管理变得更加简单高效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值