TvTaskCacheService.java 2.61 KB
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);
        }
    }
}