package com.xueyi.system.emcs.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.time.Duration;
import java.util.List;

/**
 * @author yk
 * @description
 * @date 2023-05-12 14:22
 */
@Component
public class BaseRedisListDataCache {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    private Integer size;

    public BaseRedisListDataCache init( Integer size) {
        this.size = size;
        return this;
    }


    public void addToList(String key, Serializable value) {
        // 将新值添加到List中
        redisTemplate.opsForList().rightPush(key, value);

        // 如果List长度超过设定值，则淘汰最早的元素
        if (redisTemplate.opsForList().size(key) > size) {
            redisTemplate.opsForList().leftPop(key);
        }
    }

    public List<Serializable> getList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }


    public void setListExpiration(String key, Duration duration) {
        redisTemplate.expire(key, duration);
    }
}
