package com.chinacreator.video.util;

import java.nio.charset.Charset;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

/**
 * 指定redis的key前缀
 * @author Administrator
 *
 */
@Component
public class MyStringSerializer implements RedisSerializer<String> {
	
	@Autowired
	private OtherProperties otherProperties;
	
    private final Charset charset;

    public MyStringSerializer() {
        this.charset = Charset.forName ( "UTF8" );
    }

    @Override
    public String deserialize(byte[] bytes) {
    	//获取配置文件中的属性值
        String keyPrefix = otherProperties.getRediskeyprefix(); //otherProperties.getEnv().getProperty("rediskeyprefix"); //"univideo_db_";
        String saveKey = new String ( bytes, charset );
        int indexOf = saveKey.indexOf ( keyPrefix );
        saveKey = saveKey.substring ( indexOf );

        return (saveKey.getBytes () == null ? null : saveKey);
    }

    @Override
    public byte[] serialize(String string) {
        String keyPrefix =  otherProperties.getRediskeyprefix(); //otherProperties.getEnv().getProperty("rediskeyprefix"); //"univideo_db_";
        String key = keyPrefix + string;
        return (key == null ? null : key.getBytes ( charset ));
    }
}
