springboot如何提升redis获取数据的时间

2021-10-22 10:31:00
admin
原创
208
摘要:springboot如何提升redis获取数据的时间

1、当redis里面的数据是json字符串,而且数据量很大的时候,通过key获取redis里面的数据用很慢

本地redis获取会有50ms,把json串序列化一下,之后在获取解析,只需要0点几毫秒

序列化工具用的goolgle的protostuff,下面是摘抄的一部分关于他的介绍

2、redis放数据和获取数据代码

 /***
     * 放序列化的数据
     * @param key
     * @param value
     * @param expireTime
     * @param <V>
     */
    public <V> void setSerializer(String key, V value, long expireTime) {
        setBytes(key, ProtoBufUtils.serializer(value), expireTime);
    }
    public <V> void setSerializer(String key, V value) {
        setBytes(key, ProtoBufUtils.serializer(value), DEFAULT_EXPIRE);
    }
    private void setBytes(final String key, final byte[] value, final Long expireSec) {
        final byte[] keyBytes = key.getBytes();
        redisTemplate.e x e cute(new RedisCallback<Object>() {
            @Override
            public String doInRedis(final RedisConnection connection)
                    throws DataAccessException {
                connection.set(keyBytes, value);
                if (expireSec != null) {
                    connection.expire(keyBytes, expireSec);
                }
                return null;
            }
        });
    }

    /**
     * 获取序列化的数据
     * @param key
     * @param clazz
     * @param <V>
     * @return
     */
    public <V> V getSerializer(String key, Class<V> clazz) {
        return ProtoBufUtils.deserializer(getBytes(key), clazz);
    }

    private byte[] getBytes(final String key) {
        return redisTemplate.e x e cute(new RedisCallback<byte[]>() {
            @Override
            public byte[] doInRedis(RedisConnection connection)
                    throws DataAccessException {
                return connection.get(key.getBytes());
            }
        });

    }

3、序列化工具类

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import lombok.extern.slf4j.Slf4j;

/**
 *
 * @author nolimits
 * @since 2021-10-19
 */
@Slf4j
public class ProtoBufUtils {
	private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();

	private static Objenesis objenesis = new ObjenesisStd(true);

	@SuppressWarnings("unchecked")
	private static <T> Schema<T> getSchema(Class<T> cls) {
		Schema<T> schema = RuntimeSchema.getSchema(cls);
		return schema;
	}

	@SuppressWarnings({ "unchecked" })
	public static <T> byte[] serializer(T obj) {
		Class<T> cls = (Class<T>) obj.getClass();
		LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
		try {
			Schema<T> schema = getSchema(cls);
			return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
		} catch (Exception e) {
			log.error("protobuf序列化失败");
			throw new IllegalStateException(e.getMessage(), e);
		} finally {
			buffer.clear();
		}
	}

	public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
		try {
			Schema<T> schema = getSchema(clazz);
			T message=schema.newMessage();
			ProtostuffIOUtil.mergeFrom(bytes, message, schema);
			return message;
		} catch (Exception e) {
			log.error("protobuf反序列化失败");
			throw new IllegalStateException(e.getMessage(), e);
		}
	}
}

    发表评论
    评论通过审核之后才会显示。
    文章分类
    联系方式
    联系人: 郑州-小万
    电话: 13803993919
    Email: 1027060531@qq.com
    QQ: 1027060531
    网址: www.wanhejia.com