二级缓存(缓存到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>
相关推荐
StephenCurryFans1 分钟前
Spring AI vs LangChain4j:Java AI开发框架完整对比指南 🚀
后端·spring
liujing102329294 分钟前
Day04_刷题niuke20250703
java·开发语言·算法
Brookty6 分钟前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
能工智人小辰20 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT21 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄23 分钟前
设计模式之外观模式
java·设计模式·外观模式
编程小白gogogo43 分钟前
Spring学习笔记
笔记·学习·spring
LL.。44 分钟前
同步回调和异步回调
开发语言·前端·javascript
0wioiw01 小时前
Python基础(吃洋葱小游戏)
开发语言·python·pygame
知其然亦知其所以然1 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试