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

import com.liquidnet.common.cache.redis.config.RedisKylinConfig;
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,int defaultDb,int totalDbs){
        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) {
        RedisKylinConfig redisConfig = new RedisKylinConfig();
        log.info("redisConfig.defaultDb===",redisConfig.defaultDb);
        log.info("redisConfig.totalDbs===",redisConfig.totalDbs);
//        redisConfig.getRedisTemplateByDb(MathUtil.getIndex("1",redisConfig.defaultDb,redisConfig.totalDbs));
        System.out.println(""+MathUtil.getIndex("galaxy:user:zxinchain:1222222",1,16));
    }
}
