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>