Redis && Spring Cache

发布于:2025-03-18 ⋅ 阅读:(91) ⋅ 点赞:(0)

Redis

使用方式通常为Jedis或者RedisTemplate

Jedis:

是一个独立的 Java Redis 客户端,它直接实现了 Redis 的各种命令,提供了基本的 Redis 操作功能。Jedis 不依赖于 Spring 框架,可以在任何 Java 项目中使用。
使用相对简单直接,只需要创建Jedis对象并连接到 Redis 服务器,就可以直接调用相应的方法执行 Redis 命令。

import redis.clients.jedis.Jedis;

public class JedisExample {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost", 6379);
        jedis.set("key", "value");
        String value = jedis.get("key");
        System.out.println(value);
        jedis.close();
    }
}

RedisTemplate:

是 Spring Data Redis 框架提供的一个核心类。Spring Data Redis 是 Spring 框架的一部分,它在 Redis 客户端的基础上进行了更高级的抽象和封装,使得在 Spring 应用中使用 Redis 变得更加容易和便捷,符合 Spring 的开发风格和规范。
基于 Spring 框架,使用时需要进行一些配置,例如配置 Redis 连接工厂、序列化器等。通常通过依赖注入的方式将RedisTemplate注入到需要使用的类中。

  1. 添加依赖
    在 pom.xml 中添加 Spring Data Redis 依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置 Redis 连接信息
    在 application.properties 或 application.yml 中配置 Redis 连接信息:
spring:
  redis:
    host: localhost
    port: 6379
    password:
  1. 配置 RedisTemplate
    可以通过 Java 配置类来配置 RedisTemplate,并设置序列化方式,避免默认序列化方式导致的二进制存储问题:
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.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 设置键的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置值的序列化器
        template.setValueSerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        return template;
    }
}
  1. 使用 RedisTemplate 操作 Redis
    以下是对 Redis 不同数据结构的常见操作示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class StringRedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void setStringValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String getStringValue(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }
}

Spring Cache

  1. Spring Cache 简介
    Spring 框架提供的一个抽象缓存层,它为 Java 应用程序提供了一种统一的方式来管理缓存,允许开发者通过简单的注解来实现缓存功能,而不需要关心底层具体的缓存实现。其核心优势在于:
    简化开发:通过注解的方式,减少了手动编写缓存逻辑的代码量,使开发者能够更专注于业务逻辑。
    解耦缓存实现:支持多种缓存实现,如 EhcacheRedis 等,开发者可以根据需求轻松切换不同的缓存产品,而无需对业务代码做大量修改。

  2. 基本注解
    Spring Cache 提供了多个注解来实现不同的缓存操作,以下是几个常用注解:
    @@EnableCaching:开启缓存注解功能,通常加在启动类上
    @Cacheable:主要用于方法上,当调用该方法时,Spring Cache 会先检查缓存中是否存在该方法的返回值。如果存在,则直接从缓存中获取结果并返回,不再执行方法体;如果不存在,则执行方法体,并将返回值存入缓存。
    @CachePut:同样用于方法上,无论缓存中是否存在该方法的返回值,都会执行方法体,并将返回值更新到缓存中。常用于更新操作。
    @CacheEvict:用于从缓存中移除指定的缓存项。可以指定移除单个缓存项或清空整个缓存。
    @Caching:用于组合多个缓存注解,当一个方法需要同时使用多个缓存注解时,可以使用该注解

  3. 使用步骤
    3.1 添加依赖
    如果使用 Maven 项目,在 pom.xml 中添加 Spring Boot 缓存依赖,以 Spring Boot 为例:

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

3.2 启用缓存
在 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);
    }
}

3.3 配置缓存管理器
如果使用 Redis 作为缓存,可以在配置类中配置 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.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 cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
               .entryTtl(Duration.ofMinutes(10))
               .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
               .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

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

3.4 使用缓存注解
在服务类的方法上使用缓存注解:

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

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    private final Map<Long, String> userMap = new HashMap<>();

    // 使用 @Cacheable 注解,缓存名为 users,键为用户 ID
    @Cacheable(value = "users", key = "#userId")
    public String getUser(Long userId) {
        System.out.println("Fetching user from database...");
        return userMap.get(userId);
    }

    // 使用 @CachePut 注解,更新缓存
    @CachePut(value = "users", key = "#userId")
    public String saveUser(Long userId, String userName) {
        userMap.put(userId, userName);
        return userName;
    }

    // 使用 @CacheEvict 注解,移除缓存
    @CacheEvict(value = "users", key = "#userId")
    public void deleteUser(Long userId) {
        userMap.remove(userId);
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到