欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > 二级缓存(缓存到Redis)

二级缓存(缓存到Redis)

2025/1/13 7:30:13 来源:https://blog.csdn.net/weixin_53515812/article/details/145100542  浏览:    关键词:二级缓存(缓存到Redis)

 Spring缓存

spring:redis:host: redis-server # Redis 服务器地址port: 6379password: yourpassword # 如果有密码则填写database: 0cache: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 {@Beanpublic 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: localhostport: 6379password:  # 如果有密码则填写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); // 连接 Redisthis.objectMapper = new ObjectMapper();}@Overridepublic String getId() {return this.id;}@Overridepublic void putObject(Object key, Object value) {try {// 将对象序列化为 JSON 并存储到 RedisString jsonValue = objectMapper.writeValueAsString(value);jedis.hset(id, key.toString(), jsonValue);} catch (Exception e) {throw new RuntimeException("Failed to put object into Redis cache", e);}}@Overridepublic 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);}}@Overridepublic Object removeObject(Object key) {// 从 Redis 中删除缓存return jedis.hdel(id, key.toString());}@Overridepublic void clear() {// 清空 Redis 中当前命名空间的所有缓存jedis.del(id);}@Overridepublic int getSize() {// 获取当前命名空间的缓存数量return jedis.hlen(id).intValue();}@Overridepublic ReadWriteLock getReadWriteLock() {// 返回一个读写锁(MyBatis 要求实现,但 Redis 本身是线程安全的,可以不使用)return new ReentrantReadWriteLock();}
}
<mapper namespace="com.example.mapper.UserMapper"><cache type="com.example.cache.RedisCache"/><!-- 其他 SQL 配置 -->
</mapper>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com