Spring Boot应用中基于Jedis配置@Cacheable注解的方法
基于Jedis实现Spring Cache自定义CacheManager方案
一、必备依赖
确保项目中引入以下依赖(以Maven为例):
<!-- Spring Cache 核心依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.2.8.RELEASE</version> </dependency> <!-- Jedis 客户端 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version><!-- 适配Spring Boot 2.3.x的稳定版本 --> </dependency> <!-- Spring Boot缓存启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> <version>2.3.3.RELEASE</version> </dependency>
二、自定义JedisCache实现
实现Spring的Cache接口,封装Jedis的缓存操作逻辑:
import org.springframework.cache.Cache; import org.springframework.cache.support.SimpleValueWrapper; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.io.*; import java.util.concurrent.Callable; public class JedisCache implements Cache { private final String name; private final JedisPool jedisPool; private final int expireSeconds; public JedisCache(String name, JedisPool jedisPool, int expireSeconds) { this.name = name; this.jedisPool = jedisPool; this.expireSeconds = expireSeconds; } @Override public String getName() { return this.name; } @Override public Object getNativeCache() { return this.jedisPool; } @Override public ValueWrapper get(Object key) { try (Jedis jedis = jedisPool.getResource()) { byte[] valueBytes = jedis.get(serialize(key)); return valueBytes == null ? null : new SimpleValueWrapper(deserialize(valueBytes)); } catch (Exception e) { throw new RuntimeException("获取缓存失败", e); } } @Override public <T> T get(Object key, Class<T> type) { ValueWrapper wrapper = get(key); return wrapper != null ? type.cast(wrapper.get()) : null; } @Override public <T> T get(Object key, Callable<T> valueLoader) { ValueWrapper wrapper = get(key); if (wrapper != null) { return (T) wrapper.get(); } try { T value = valueLoader.call(); put(key, value); return value; } catch (Exception e) { throw new RuntimeException("加载缓存值失败", e); } } @Override public void put(Object key, Object value) { try (Jedis jedis = jedisPool.getResource()) { byte[] keyBytes = serialize(key); byte[] valueBytes = serialize(value); jedis.setex(keyBytes, expireSeconds, valueBytes); } catch (Exception e) { throw new RuntimeException("存入缓存失败", e); } } @Override public ValueWrapper putIfAbsent(Object key, Object value) { try (Jedis jedis = jedisPool.getResource()) { byte[] keyBytes = serialize(key); byte[] valueBytes = serialize(value); String result = jedis.set(keyBytes, valueBytes, "NX", "EX", expireSeconds); if ("OK".equals(result)) { return null; } else { byte[] existingValue = jedis.get(keyBytes); return existingValue != null ? new SimpleValueWrapper(deserialize(existingValue)) : null; } } catch (Exception e) { throw new RuntimeException("存入缓存(不存在则添加)失败", e); } } @Override public void evict(Object key) { try (Jedis jedis = jedisPool.getResource()) { jedis.del(serialize(key)); } catch (Exception e) { throw new RuntimeException("删除缓存失败", e); } } @Override public void clear() { // 生产环境建议给缓存键加前缀,避免清空整个Redis try (Jedis jedis = jedisPool.getResource()) { jedis.flushDB(); } catch (Exception e) { throw new RuntimeException("清空缓存失败", e); } } // JDK序列化 private byte[] serialize(Object obj) throws IOException { if (obj == null) return null; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(obj); return bos.toByteArray(); } } // JDK反序列化 private Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { if (bytes == null) return null; try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis)) { return ois.readObject(); } } }
三、自定义JedisCacheManager实现
实现Spring的CacheManager接口,管理JedisCache实例:
import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import redis.clients.jedis.JedisPool; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class JedisCacheManager implements CacheManager { private final JedisPool jedisPool; private final int defaultExpireSeconds; private final Map<String, Cache> cacheMap = new HashMap<>(); public JedisCacheManager(JedisPool jedisPool, int defaultExpireSeconds) { this.jedisPool = jedisPool; this.defaultExpireSeconds = defaultExpireSeconds; } @Override public Cache getCache(String name) { return cacheMap.computeIfAbsent(name, k -> new JedisCache(k, jedisPool, defaultExpireSeconds)); } @Override public Collection<String> getCacheNames() { return cacheMap.keySet(); } }
四、配置Bean并开启缓存
创建配置类,初始化Jedis连接池和自定义CacheManager:
import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; @Configuration @EnableCaching public class CacheConfig { @Bean public JedisPool jedisPool() { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(100); poolConfig.setMaxIdle(20); poolConfig.setMinIdle(5); poolConfig.setTestOnBorrow(true); // 根据你的Redis服务配置调整参数 return new JedisPool(poolConfig, "localhost", 6379, 3000, null); } @Bean public JedisCacheManager jedisCacheManager(JedisPool jedisPool) { // 默认缓存过期时间3600秒 return new JedisCacheManager(jedisPool, 3600); } }
五、使用@Cacheable注解
在业务方法上直接使用Spring缓存注解即可:
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserService { @Cacheable(value = "userCache", key = "#userId") public User getUserById(Long userId) { // 模拟数据库查询逻辑 System.out.println("查询数据库,userId: " + userId); return new User(userId, "testUser", "test@example.com"); } } // 实体类需实现Serializable(适配JDK序列化) class User implements Serializable { private Long id; private String username; private String email; // 构造方法、getter、setter省略 }
注意事项
- 序列化优化:示例用JDK序列化,生产环境可替换为Jackson序列化(更高效、可读性更好),只需修改
serialize和deserialize方法。 - 键前缀:建议给每个缓存空间的键添加前缀(如
userCache:userId),避免不同缓存的键冲突。 - 连接池配置:根据实际并发量调整JedisPool的连接数参数,避免连接耗尽。
- 异常处理:可根据业务需求自定义异常捕获逻辑,替换示例中的RuntimeException。
内容的提问来源于stack exchange,提问作者Jessi
相关产品推荐
相关产品推荐

