redis+springcache

在 Spring 框架中,Spring Cache 是一个用于简化缓存操作的抽象层,而 Redis 是一种常用的高性能键值存储系统,常被用作缓存数据库。通过将 Redis 与 Spring Cache 集成,可以轻松实现基于 Redis 的缓存管理。

以下是使用 Redis 和 Spring Cache 的基本步骤和配置说明:


1. 添加依赖

在 Maven 或 Gradle 中添加必要的依赖项。

Maven 示例:
<dependencies>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-cacheartifactId>
    dependency>

    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>

    
    <dependency>
        <groupId>redis.clientsgroupId>
        <artifactId>jedisartifactId>
    dependency>
dependencies>
Gradle 示例:
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'redis.clients:jedis'

2. 配置 Redis

application.ymlapplication.properties 文件中配置 Redis 连接信息。

application.yml 示例:
spring:
  redis:
    host: localhost # Redis 服务器地址
    port: 6379      # Redis 端口
    password:       # Redis 密码(如果没有密码则留空)
    timeout: 5000ms # 超时时间
    lettuce:
      pool:
        max-active: 8   # 最大连接数
        max-idle: 8     # 最大空闲连接数
        min-idle: 0     # 最小空闲连接数
application.properties 示例:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=5000
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0

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 Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4. 配置 RedisCacheManager

通过配置 RedisCacheManager 来定义 Redis 缓存的行为。

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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

@Configuration
public class CacheConfig {

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(10)) // 设置缓存过期时间为 10 分钟
                .disableCachingNullValues()      // 不缓存 null 值
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer())); // 使用 JSON 序列化

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(cacheConfiguration)
                .build();
    }
}

5. 使用缓存注解

Spring Cache 提供了一些注解来简化缓存操作。常用注解包括:

  • @Cacheable:从缓存中读取数据,如果缓存中没有,则执行方法并将结果存入缓存。
  • @CachePut:更新缓存中的数据。
  • @CacheEvict:清除缓存中的数据。
  • @Caching:组合多个缓存操作。
示例代码:
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) {
        // 模拟从数据库中获取用户
        System.out.println("Fetching user from database for ID: " + id);
        return new User(id, "User" + id);
    }

    @CachePut(value = "users", key = "#user.id")
    public User updateUser(User user) {
        // 更新用户信息
        System.out.println("Updating user in cache: " + user);
        return user;
    }

    @CacheEvict(value = "users", key = "#id")
    public void deleteUser(Long id) {
        // 删除用户信息
        System.out.println("Deleting user from cache: " + id);
    }
}

6. 测试缓存功能

编写测试代码来验证缓存是否正常工作。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}

访问 /user/1 时,第一次会触发数据库查询并缓存结果,后续访问将直接从 Redis 中读取缓存数据。


7. 监控 Redis 缓存

可以通过 Redis 客户端工具(如 redis-cli 或 Redis Desktop Manager)查看缓存内容。

例如,使用 redis-cli 查看所有缓存键:

keys *

总结

通过结合 Redis 和 Spring Cache,可以快速实现基于 Redis 的分布式缓存功能。Spring Cache 提供了简洁的注解方式,降低了缓存管理的复杂性。根据实际需求,还可以进一步优化 Redis 的配置,例如设置不同的缓存过期时间、序列化方式等。

你可能感兴趣的:(redis,java,spring,boot)