package com.youchain.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.function.Supplier;


/**
 * 缓存对象通用工具类
 */
@Component
public class RedisObjectUtils {

    private final RedisUtils redisUtils;

    @Autowired
    public RedisObjectUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }


    public <T> T getObjectFromCache(String cacheKey, Supplier<T> serviceSupplier, String errorMessage) {
        T object = null;
        boolean flag = redisUtils.hasKey(cacheKey);
        if (flag) {
            object = (T) redisUtils.get(cacheKey);
        } else {
            object = getOrThrow(Optional.ofNullable(serviceSupplier.get()), errorMessage);
            redisUtils.set(cacheKey, object);
        }
        return object;
    }

    public static <T> T getOrThrow(Optional<T> optional, String errorMessage) {
        return optional.orElseThrow(() -> new IllegalArgumentException(errorMessage));
    }

}
