package com.cf.imes.framework.organ.core.redis;

import com.cf.imes.framework.redis.core.TimeoutRedisCacheManager;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

/**
 * 多组织的 {@link RedisCacheManager} 实现类
 *
 * 操作指定 name 的 {@link Cache} 时，自动拼接组织后缀，格式为 name + ":" + organId + 后缀
 *
 * @author airhead
 */
@Slf4j
public class OrganRedisCacheManager extends TimeoutRedisCacheManager {

    public OrganRedisCacheManager(RedisCacheWriter cacheWriter,
                                  RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    public Cache getCache(String name) {
        // 如果开启多组织，则 name 拼接组织后缀
        if (!OrganContextHolder.isIgnore()
            && OrganContextHolder.getOrganId() != null) {
            name = name + ":" + OrganContextHolder.getOrganId();
        }

        // 继续基于父方法
        return super.getCache(name);
    }

}
