二级缓存(缓存到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>
相关推荐
крон2 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan2 小时前
c++ 单例模式
开发语言·c++·单例模式
coderSong25682 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
Mr_Air_Boy3 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
曹勖之3 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?4 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头4 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
年老体衰按不动键盘4 小时前
快速部署和启动Vue3项目
java·javascript·vue