TvTaskCacheService.java
2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.huaheng.api.tv.controller;
import com.huaheng.framework.web.domain.TVResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
@Slf4j
@Component
public class TvTaskCacheService {
private static final String TV_TASK_CACHE_PREFIX = "tv_shipment:";
private static final long CACHE_TIMEOUT = 3; // 3秒缓存
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 从Redis获取缓存数据
*/
public TVResult getFromCache(String cacheKey) {
try {
ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
Object result = valueOps.get(cacheKey);
if (result instanceof TVResult) {
log.debug("Redis缓存命中: {}", cacheKey);
return (TVResult) result;
}
} catch (Exception e) {
log.error("Redis缓存访问异常, key: {}", cacheKey, e);
}
return null;
}
/**
* 设置Redis缓存
*/
public void setCache(String cacheKey, TVResult result) {
try {
ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
valueOps.set(cacheKey, result, CACHE_TIMEOUT, TimeUnit.SECONDS);
log.debug("Redis缓存设置成功: {}", cacheKey);
} catch (Exception e) {
log.error("Redis缓存设置异常, key: {}", cacheKey, e);
}
}
/**
* 生成缓存Key
*/
public String generateCacheKey(List<String> portList) {
String ports = String.join(",", portList);
return TV_TASK_CACHE_PREFIX + ports;
}
/**
* 简单的互斥锁机制,防止缓存击穿
*/
public boolean acquireLock(String lockKey) {
try {
ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
// 使用SETNX实现简单锁,1秒过期
return valueOps.setIfAbsent(lockKey, "LOCKED", 1, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("获取锁异常", e);
return false;
}
}
/**
* 释放锁
*/
public void releaseLock(String lockKey) {
try {
redisTemplate.delete(lockKey);
} catch (Exception e) {
log.error("释放锁异常", e);
}
}
}