package com.liquidnet.common.cache.redis.util;

import com.liquidnet.common.cache.redis.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: MathUtil
 * @Package com.liquidnet.common.cache.redis.util
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/8/10 18:03
 */
@Slf4j
public class MathUtil {
    public static int getIndex(String key){
        log.debug("MathUtil.getIndex key:{} hashcode:{}",key,key.hashCode());
        int defaultDb = RedisConfig.defaultDb;
        int totalDbs = RedisConfig.totalDbs;
        if(totalDbs==1){
            log.info("only one db : {} ",defaultDb);
            return defaultDb;
        }
        int mod = 250;
        if(totalDbs > 1 && totalDbs < 256){
            if(totalDbs==16){
                mod = 15;
            }else{
                mod = totalDbs - 1;
            }
        }
        long value = Long.valueOf(key.hashCode());
        int hash=(int)(value ^ (value >>> 32));
        int index=hash % mod;
        log.debug("MathUtil.getIndex key:{} index:{}",key,index);
        return index;
    }

    public static void main(String[] args) {
        RedisConfig redisConfig = new RedisConfig();
        redisConfig.getRedisTemplateByDb(MathUtil.getIndex("1"));
    }
}
