二级缓存(缓存到Redis)

Spring缓存

复制代码
spring:
  redis:
    host: redis-server # Redis 服务器地址
    port: 6379
    password: yourpassword # 如果有密码则填写
    database: 0
  cache:
    type: redis # 使用 Redis 作为缓存

<!-- Spring Boot Starter Cache -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<!-- Spring Boot Starter Data Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- Jackson 用于 JSON 序列化 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>


@SpringBootApplication
@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 java.time.Duration;

@Configuration
public class RedisCacheConfig {

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 配置缓存默认设置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer())) // 使用 JSON 序列化
                .entryTtl(Duration.ofMinutes(30)); // 设置缓存过期时间

        // 创建 Redis 缓存管理器
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .build();
    }
}

mybatis二级缓存

复制代码
<!-- Spring Boot Starter Data Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

spring:
  redis:
    host: localhost
    port: 6379
    password:  # 如果有密码则填写
    database: 0 # 默认数据库
mybatis:
  configuration:
    cache-enabled: true # 启用全局二级缓存

import org.apache.ibatis.cache.Cache;
import redis.clients.jedis.Jedis;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache {

    private final String id; // MyBatis 缓存 ID(通常是 Mapper 的命名空间)
    private final Jedis jedis; // Redis 客户端
    private final ObjectMapper objectMapper; // JSON 序列化工具

    public RedisCache(String id) {
        this.id = id;
        this.jedis = new Jedis("localhost", 6379); // 连接 Redis
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        try {
            // 将对象序列化为 JSON 并存储到 Redis
            String jsonValue = objectMapper.writeValueAsString(value);
            jedis.hset(id, key.toString(), jsonValue);
        } catch (Exception e) {
            throw new RuntimeException("Failed to put object into Redis cache", e);
        }
    }

    @Override
    public Object getObject(Object key) {
        try {
            // 从 Redis 中获取 JSON 并反序列化为对象
            String jsonValue = jedis.hget(id, key.toString());
            return jsonValue != null ? objectMapper.readValue(jsonValue, Object.class) : null;
        } catch (Exception e) {
            throw new RuntimeException("Failed to get object from Redis cache", e);
        }
    }

    @Override
    public Object removeObject(Object key) {
        // 从 Redis 中删除缓存
        return jedis.hdel(id, key.toString());
    }

    @Override
    public void clear() {
        // 清空 Redis 中当前命名空间的所有缓存
        jedis.del(id);
    }

    @Override
    public int getSize() {
        // 获取当前命名空间的缓存数量
        return jedis.hlen(id).intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        // 返回一个读写锁(MyBatis 要求实现,但 Redis 本身是线程安全的,可以不使用)
        return new ReentrantReadWriteLock();
    }
}

<mapper namespace="com.example.mapper.UserMapper">
    <cache type="com.example.cache.RedisCache"/>
    <!-- 其他 SQL 配置 -->
</mapper>
相关推荐
编程(变成)小辣鸡1 小时前
如何防止接口被恶意刷?
java·后端·网络安全
Helen_cai1 小时前
OpenHarmony 完整项目工程整合规范 + 模块化分层架构(API23+ 标准企业级结构)
开发语言·华为·php·harmonyos
大圣编程6 小时前
Java 多维数组详解
java·开发语言
万法若空8 小时前
【算法-查找】查找算法
java·数据结构·算法
殳翰9 小时前
下服务器端开发流程及相关工具介绍(C++)
开发语言·c++
落寞的星星9 小时前
这个对象就包含了已经转换好的DFA和各种词法分析器运转所需要的参数。下一步,我们就可以用ScannerInfo对象创建出Scanner对象,请看下面的代码:
开发语言·c#
nothing&nowhere9 小时前
用 Python 做问卷数据清洗:无效样本检测与处理实战
开发语言·python·数据清洗·数据处理·问卷星·问卷星脚本·刷问卷
2601_9615934210 小时前
Rust 开发环境配置繁琐?RustRover 开箱即用搞定编码调试
开发语言·后端·macos·rust
HZZD_HZZD10 小时前
DL/T 645-2026新国标深度解读与智能电表协议适配实战:从帧结构变化到Java采集器升级的全链路改造方案
java·开发语言
多加点辣也没关系12 小时前
JavaScript|第4章:类型转换
开发语言·javascript