package com.ruoyi.common.core.redis;

import org.springframework.data.redis.serializer.RedisSerializer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 为redis key 统一加上前缀
 */
public class RedisKeySerializer implements RedisSerializer<String> {

    /**
     * 编码格式
     */
    private final Charset charset;

    /**
     * 前缀
     */
    private final String PREFIX_KEY = "V2:";

    public RedisKeySerializer() {
        this(StandardCharsets.UTF_8);
    }

    public RedisKeySerializer(Charset charset) {
        this.charset = charset;
    }

    @Override
    public String deserialize(byte[] bytes) {
        String saveKey = new String(bytes, charset);
        int indexOf = saveKey.indexOf(PREFIX_KEY);
        if (indexOf > 0) {
            System.out.println("key缺少前缀");
        } else {
            saveKey = saveKey.substring(indexOf);
        }
        return saveKey;
    }

    @Override
    public byte[] serialize(String string) {
        String key = PREFIX_KEY + string;
        return key.getBytes(charset);
    }
}
