二级缓存(缓存到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>
相关推荐
电子_咸鱼25 分钟前
【STL string 全解析:接口详解、测试实战与模拟实现】
开发语言·c++·vscode·python·算法·leetcode
哈茶真的c1 小时前
【书籍心得】左耳听风:传奇程序员练级攻略
java·c语言·python·go
喝养乐多长不高1 小时前
JAVA微服务脚手架项目详解(三)
java·大数据·微服务·文件·地图·oss
沐知全栈开发1 小时前
ionic 选项卡栏操作详解
开发语言
曹牧1 小时前
C#中,#region和#endregion
开发语言·c#
顾安r1 小时前
11.22 脚本打包APP 排错指南
linux·服务器·开发语言·前端·flask
万邦科技Lafite1 小时前
1688图片搜索商品API接口(item_search_img)使用指南
java·前端·数据库·开放api·电商开放平台
落落落sss1 小时前
java实现排序
java·数据结构·算法
czhc11400756631 小时前
c# 1121 构造方法
java·javascript·c#
蒙小萌19932 小时前
Swift UIKit MVVM + RxSwift Development Rules
开发语言·prompt·swift·rxswift