Files
MedicineManagerSystem/backend/src/main/java/com/kronecker/backend/utils/RedisCacheService.java
KiriAky 107 b764f6fa59 添加Redis缓存支持和Docker部署配置
- 新增Redis缓存功能,用于优化仪表板统计数据查询性能
- 添加Redis连接池管理和自动降级机制,无连接时自动跳过缓存
- 配置Dockerfile支持前后端容器化部署
- 添加docker-compose编排文件实现一键部署
- 更新README文档包含新的部署方式和架构说明
- 在入库出库操作后清除相关缓存以保证数据一致性
2026-07-07 10:08:33 +08:00

112 lines
3.1 KiB
Java

package com.kronecker.backend.utils;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Slf4j
@Component
public class RedisCacheService {
@Value("${REDIS_HOST:localhost}")
private String host;
@Value("${REDIS_PORT:6379}")
private int port;
@Value("${REDIS_PASSWORD:}")
private String password;
@Value("${REDIS_TIMEOUT:2000}")
private int timeout;
private JedisPool pool;
private boolean available = false;
@PostConstruct
public void init() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(8);
config.setMaxIdle(4);
config.setMinIdle(1);
pool = (password != null && !password.isEmpty())
? new JedisPool(config, host, port, timeout, password)
: new JedisPool(config, host, port, timeout);
// 测试连接
try (Jedis jedis = pool.getResource()) {
jedis.ping();
}
available = true;
log.info("Redis 连接成功: {}:{}", host, port);
} catch (Exception e) {
available = false;
pool = null;
log.warn("Redis 不可用 ({}:{}),跳过缓存: {}", host, port, e.getMessage());
}
}
@PreDestroy
public void destroy() {
if (pool != null) pool.close();
}
public boolean enabled() {
return available && pool != null;
}
public void set(String key, String value, long seconds) {
if (!enabled()) return;
try (Jedis jedis = pool.getResource()) {
jedis.setex(key, seconds, value);
} catch (Exception e) {
log.warn("Redis set {} 失败: {}", key, e.getMessage());
}
}
public String get(String key) {
if (!enabled()) return null;
try (Jedis jedis = pool.getResource()) {
return jedis.get(key);
} catch (Exception e) {
log.warn("Redis get {} 失败: {}", key, e.getMessage());
return null;
}
}
// === Object 序列化方法 ===
public void setObject(String key, Object value, long seconds) {
if (value == null) return;
set(key, JSONUtil.toJsonStr(value), seconds);
}
public <T> T getObject(String key, Class<T> clazz) {
String json = get(key);
if (json == null) return null;
try {
return JSONUtil.toBean(json, clazz);
} catch (Exception e) {
log.warn("Redis 反序列化 {} 失败: {}", key, e.getMessage());
return null;
}
}
public void delete(String key) {
if (!enabled()) return;
try (Jedis jedis = pool.getResource()) {
jedis.del(key);
} catch (Exception e) {
log.warn("Redis del {} 失败: {}", key, e.getMessage());
}
}
}