赞
踩
系列化前通过redisTemplate.opsForHash().put进去的数据带有类信息
系列换成byte类型,不再带有类信息,节省空间。
- import com.fasterxml.jackson.annotation.JsonAutoDetect;
- import com.fasterxml.jackson.annotation.PropertyAccessor;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.fasterxml.jackson.databind.SerializationFeature;
- import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
- import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
-
- /**
- * @author czmao
- * @Description RedisConfig
- * @since 2023/8/11 0:30
- */
- @Configuration
- public class RedisConfig {
-
- @Bean("orderRedisTemplate")
- public RedisTemplate<String, Object> baseRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
-
- RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
- redisTemplate.setConnectionFactory(redisConnectionFactory);
- //创建JSON序列化工具
- Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
- // 创建JSON序列化工具
- //GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
-
-
- //序列化时将类的数据类型存入json,以便反序列化的时候转换成正确的类型
- ObjectMapper objectMapper = new ObjectMapper();
- //将当前对象的数据类型也存入序列化的结果字符串中,以便反序列化
- objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
-
- // 解决jackson2无法反序列化LocalDateTime的问题
- objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
- objectMapper.registerModule(new JavaTimeModule());
- objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
- jsonRedisSerializer.setObjectMapper(objectMapper);
-
- //首先key的序列化方式
- StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
- redisTemplate.setKeySerializer(stringRedisSerializer);
- // 设置值的序列化器
- redisTemplate.setValueSerializer(jsonRedisSerializer);
- redisTemplate.afterPropertiesSet();
-
- return redisTemplate;
- }
- }
- import java.lang.reflect.Type;
-
- /**
- * @author czmao
- * @description CommonSerializer
- * @since 2023/9/19 21:59
- */
- public interface CommonSerializer {
- byte[] serialize(Type var1, Object var2);
-
- Object deserialize(byte[] var1, Type var2);
- }
系列化和反系列化的JSON要持一致 这里选择fastjson,可以根据实际情况选择
- import com.alibaba.fastjson.JSON;
- import com.vanchan.sca.order.service.CommonSerializer;
- import org.apache.commons.lang3.StringUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.stereotype.Component;
-
- import java.lang.reflect.Type;
- import java.nio.charset.Charset;
-
- /**
- * @author czmao
- * @Description CommonJacksonSerializer
- * @since 2023/9/19 22:00
- */
- @Component
- public class CommonJacksonSerializer implements CommonSerializer {
- private static final Logger LOGGER = LoggerFactory.getLogger(CommonJacksonSerializer.class);
-
- public static final Charset DEFAULT_CHARSET_INSTANCE = Charset.forName("UTF-8");
-
- public CommonJacksonSerializer() {
-
- }
-
- @Override
- public byte[] serialize(Type var1, Object ob) {
- if (ob == null) {
- return new byte[0];
- } else {
- String result = JSON.toJSONString(ob);
- return StringUtils.isEmpty(result) ? new byte[0] : result.getBytes(DEFAULT_CHARSET_INSTANCE);
- }
- }
-
- @Override
- public Object deserialize(byte[] bytes, Type type) {
- try {
- return JSON.parseObject(new String(bytes), type);
- } catch (Exception var4) {
- LOGGER.error(var4.getMessage(), var4);
- return null;
- }
- }
- }
- package com.vanchan.sca.order.service;
-
- import java.util.Collection;
- import java.util.List;
- import java.util.Map;
- import java.util.concurrent.TimeUnit;
-
- /**
- * @author czmao
- * @description redis系列化操作数据入口
- * @since 2023/9/19 14:39
- */
- public interface CommonRedisCacheService {
-
- /**
- * 普通类型String 推送
- *
- * @param var1
- * @param var2
- */
- <V> void put(String var1, V var2, Long expireTime, final TimeUnit unit);
-
- /**
- * String类型key 推送
- *
- * @param var1
- * @param var2
- */
- <V> void put(String var1, V var2);
-
- /**
- * String类型key 获取
- *
- * @param key key
- * @param clazz 对象r
- */
- <V> V get(String key, Class<V> clazz);
-
-
- /**
- * set数据读取一次读一个
- *
- * @param key
- * @param aClass
- * @return
- */
- <V> V setPop(String key, Class<V> aClass);
-
- /**
- * set数据添加(批量)
- *
- * @param key
- * @param clazz
- * @return
- */
- <V> Long setAddList(String key, List<V> clazz);
-
- /**
- * set数据添加
- *
- * @param key
- * @param clazz
- * @return
- */
- <V> Long setAdd(String key, V clazz);
-
-
- /**
- * LIST 左推数据
- *
- * @param key
- * @param clazz
- * @return
- */
- <V> Long listLeftPush(String key, V clazz);
-
- /**
- * redis-set数据左读取,一次读一个
- *
- * @param key
- * @param clazz
- * @return
- */
- <V> V listLeftPop(String key, Class<V> clazz);
-
- /**
- * LIST 右推数据
- *
- * @param key 键
- * @param clazz 对象
- * @return 影响条数
- */
- <V> Long lRightPush(String key, V clazz);
-
- /**
- * LIST 右读数据
- *
- * @param key 键
- * @param clazz 对象
- * @return 反系列化对象
- */
- <V> V lRightPop(String key, Class<V> clazz);
-
- /**
- * 判断list数量
- *
- * @param key
- * @return
- */
- <V> Long length(String key);
-
- /**
- * list类型数据查询 全量
- *
- * @param key
- * @param var2
- * @return
- */
- <V> List<V> getList(String key, Class<V> var2);
-
- /**
- * list类型数据查询 指定区间
- *
- * @param key key
- * @param start 开始
- * @param end 结束
- * @param clazz
- * @return
- */
- <V> List<V> getList(String key, int start, int end, Class<V> clazz);
-
- /**
- * 根据key查询hash类 所有数据
- *
- * @param mainKey
- * @param clazz
- * @return
- */
- <V> Map<String, V> hGetAll(String mainKey, Class<V> clazz);
-
- /**
- * 根据key-key精准查询hash类数据
- *
- * @param mainKey redis主key
- * @param field 副键
- * @param clazz 对象类型
- * @return
- */
- <V> V hGet(String mainKey, String field, Class<V> clazz);
-
- /**
- * 利用双key往hashMap添加数据
- *
- * @param key
- * @param field
- * @param var3
- */
- <V> void hPut(String key, String field, V var3);
-
- /**
- * 批量往hashMap添加数据
- *
- * @param key
- * @param var3
- * @param
- */
- <V> void hPutAll(String key, Map<String, V> var3);
-
- /**
- * 根据key获取hash所有value值 返回list
- *
- * @param key
- * @return
- * @Author: chenzumao
- */
- <V> List<V> hGetAllToList(String key, Class<V> clazz);
-
- /**
- * 删除hash指定数据
- *
- * @param key key
- * @param field field
- */
- <V> void hDel(String key, String field);
-
- /**
- * 根据key和多个field获取hash相应的value值 返回list
- *
- * @param key 主键key
- * @param fields 批量获取的副键
- * @param clazz 类
- * @return 集合
- * @Author: chenzumao
- */
- <V> List<V> hGetAllToList(String key, Collection<String> fields, Class<V> clazz);
-
-
- /**
- * 危险操作-删除该key所有数据
- *
- * @param key
- * @return
- */
- <V> Long delKey(String key);
- }
- package com.vanchan.sca.order.service.impl;
-
-
- import com.alibaba.fastjson.JSON;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.vanchan.sca.order.service.CommonRedisCacheService;
- import com.vanchan.sca.order.service.CommonSerializer;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.collections4.CollectionUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.dao.DataAccessException;
- import org.springframework.data.redis.connection.RedisConnection;
- import org.springframework.data.redis.connection.RedisStringCommands;
- import org.springframework.data.redis.core.RedisCallback;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.core.types.Expiration;
- import org.springframework.stereotype.Component;
-
- import javax.annotation.Resource;
- import java.lang.reflect.Type;
- import java.nio.charset.StandardCharsets;
- import java.util.*;
- import java.util.concurrent.TimeUnit;
- import java.util.stream.Collectors;
-
- /**
- * @author czmao
- * @Description redis系列化实现类
- * @since 2023/8/16 8:40
- */
-
- @Component(value = "orderRedisCacheService")
- @Slf4j
- public class CommonRedisCacheServiceImpl implements CommonRedisCacheService {
- @Resource(name = "orderRedisTemplate")
- private RedisTemplate<String, byte[]> redisTemplate;
- private ObjectMapper objectMapper;
-
- @Autowired
- private CommonSerializer serializer;
-
- public CommonRedisCacheServiceImpl() {
- super();
- this.objectMapper = new ObjectMapper();
- }
-
- /**
- * 系列化:将给定的对象序列化为JSON字节数组
- *
- * @param value
- * @return 数组
- */
- public byte[] serialize(Object value) {
- byte[] bytes = null;
- try {
- bytes = objectMapper.writeValueAsBytes(value);
- } catch (Exception e) {
- log.error("Failed to serialize and save data to Redis", e);
- }
- return bytes;
- }
-
- /**
- * 系列化List集合
- *
- * @param values
- * @return
- */
- byte[][] serializeValues(Collection<?> values) {
- byte[][] rawValues = new byte[values.size()][];
- int i = 0;
-
- Object value;
- for (Iterator<?> iterator = values.iterator(); iterator.hasNext(); rawValues[i++] = this.serialize(value)) {
- value = iterator.next();
- }
-
- return rawValues;
- }
-
- /**
- * 反系列化:从Redis中检索字节数组并将其反序列化为给定类型的对象
- *
- * @param data redis数据
- * @param valueType 转换对象
- * @return
- */
- public <V> V deserialize(byte[] data, Class<V> valueType) {
- if (data == null) {
- return null;
- }
- try {
- return (V) serializer.deserialize(data, valueType);
- } catch (Exception e) {
- log.error("Failed to retrieve and deserialize data from Redis", e);
- }
- return null;
- }
-
- /**
- * 系列化字符串
- *
- * @param value
- * @return
- */
- private byte[] serializeForString(String value) {
- return value == null ? null : value.getBytes(StandardCharsets.UTF_8);
- }
-
- /**
- * 获取指定变量中的value值
- *
- * @param key
- * @return
- * @Author: chenzumao
- */
- @Override
- public <V> List<V> hGetAllToList(String key, Class<V> clazz) {
- List<V> objectList = new ArrayList<>();
- byte[] keyBytes = serializeForString(key);
- if (this.hasKey(key)) {
- List<byte[]> dataBytes = this.redisTemplate.execute(connection -> connection.hVals(keyBytes), true);
- objectList = deserializeList(dataBytes, clazz);
- }
-
- return objectList;
- }
-
- /**
- * 根据key和多个field获取hash相应的value值 返回list
- *
- * @param key 主键key
- * @param fields 批量获取的副键
- * @param clazz 类
- * @return 集合
- * @Author: chenzumao
- */
- @Override
- public <V> List<V> hGetAllToList(String key, Collection<String> fields, Class<V> clazz) {
- List<V> objectList = new ArrayList<>();
- byte[] keyBytes = serializeForString(key);
- if (CollectionUtils.isEmpty(fields)) {
- return objectList;
- }
- List<String> collect = fields.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
- if (CollectionUtils.isEmpty(collect)) {
- return objectList;
- }
-
- byte[][] rawHashKeys = new byte[collect.size()][];
- int counter = 0;
- for (String hashKey : fields) {
- rawHashKeys[counter++] = serializeForString(hashKey);
- }
-
- if (this.hasKey(keyBytes)) {
- List<byte[]> dataBytes = this.redisTemplate.execute(connection -> connection.hMGet(keyBytes, rawHashKeys), true);
- objectList = deserializeList(dataBytes, clazz);
- }
-
- return objectList;
- }
-
-
- /**
- * List反系列化
- *
- * @param dataBytes 查询到的数据
- * @param clazz 类
- * @return
- */
- private <V> List<V> deserializeList(List<byte[]> dataBytes, Class<V> clazz) {
- List<V> dataList = new ArrayList<>();
- if (CollectionUtils.isEmpty(dataBytes)) {
- return dataList;
- } else {
- Iterator<byte[]> iterator = dataBytes.iterator();
- while (iterator.hasNext()) {
- byte[] next = iterator.next();
- if (null == next || next.length == 0) {
- continue;
- }
- V dataInfo = this.deserialize(next, clazz);
- if (null != dataInfo) {
- dataList.add(dataInfo);
- }
- }
- }
- return dataList;
- }
-
-
- <V extends Collection<?>> V deserializeValues(Collection<byte[]> rawValues, Class<?> collectionType, Class<V> type) {
- if (rawValues == null) {
- return (V) new ArrayList<>();
- } else {
- Collection<Object> values = List.class.isAssignableFrom(collectionType) ? new ArrayList<>(rawValues.size()) : new LinkedHashSet<>(rawValues.size());
- Iterator<byte[]> var5 = rawValues.iterator();
-
- while (var5.hasNext()) {
- byte[] bs = var5.next();
- values.add(this.deserialize(bs, type));
- }
-
- return (V) values;
- }
- }
-
- /**
- * 把value系列化存byte
- *
- * @param value
- * @param <V>
- * @return
- */
-
- private <V> byte[] serializeToString(V value) {
- return null == value ? new byte[0] : this.serializer.serialize((Type) null, value);
- }
-
- /**
- * 基本类型数据操作
- *
- * @param key key
- * @param value value byte
- * @param expireSec 过期时间 毫秒
- */
- private void doPut(String key, final byte[] value, final long expireSec) {
- final byte[] keyBytes = this.serializeForString(key);
- this.redisTemplate.execute(new RedisCallback<Object>() {
- public String doInRedis(RedisConnection connection) throws DataAccessException {
- if (expireSec > 0L) {
- connection.set(keyBytes, value, Expiration.milliseconds(expireSec), RedisStringCommands.SetOption.UPSERT);
- } else {
- connection.set(keyBytes, value);
- }
-
- return null;
- }
- });
- }
-
- /**
- * 普通类型String 推送
- *
- * @param key key
- * @param var2 value
- */
- @Override
- public <V> void put(String key, V var2, Long expireTime, final TimeUnit unit) {
- byte[] valueBytes = serializeToString(var2);
- long time = 0;
- if (null != expireTime) {
- time = unit.toMillis(expireTime);
- }
- this.doPut(key, valueBytes, time);
- }
-
- /**
- * 普通类型String 推送
- *
- * @param key key
- * @param var2 value
- */
- @Override
- public <V> void put(String key, V var2) {
- byte[] valueBytes = serializeToString(var2);
- this.doPut(key, valueBytes, 0);
- }
-
- @Override
- public <V> V get(String key, Class<V> clazz) {
- byte[] byteValue = this.doGet(key);
- return byteValue == null ? null : deserialize(byteValue, clazz);
- }
-
- private byte[] doGet(final String key) {
-
- byte[] bytes = serializeForString(key);
- return this.redisTemplate.execute(new RedisCallback<byte[]>() {
- public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
- return connection.get(bytes);
- }
- });
- }
-
- /**
- * set数据读取一次读一个
- *
- * @param key
- * @param clazz
- * @return
- */
- @Override
- public <V> V setPop(String key, Class<V> clazz) {
- final byte[] keyBytes = this.serializeForString(key);
- byte[] hGetBytes = this.redisTemplate.execute(connection -> connection.sPop(keyBytes), true);
- return this.deserialize(hGetBytes, clazz);
- }
-
- /**
- * set数据添加(批量)
- *
- * @param key
- * @param values 对象集合
- * @return 影响条数
- */
- @Override
- public <V> Long setAddList(String key, List<V> values) {
- byte[][] listBytes = this.serializeValues(values);
- final byte[] keyBytes = this.serializeForString(key);
- return this.redisTemplate.execute(new RedisCallback<Long>() {
- @Override
- public Long doInRedis(RedisConnection connection) throws DataAccessException {
- return connection.sAdd(keyBytes, listBytes);
- }
- });
- }
-
- /**
- * set数据添加
- *
- * @param key 键
- * @param value 对象
- * @return 影响条数
- */
- @Override
- public <V> Long setAdd(String key, V value) {
- byte[] valueByte = this.serialize(value);
- final byte[] keyBytes = this.serializeForString(key);
- return this.redisTemplate.execute(new RedisCallback<Long>() {
- @Override
- public Long doInRedis(RedisConnection connection) throws DataAccessException {
- return connection.sAdd(keyBytes, valueByte);
- }
- });
- }
-
- /**
- * LIST 左推数据
- *
- * @param key 键
- * @param value 对象
- * @return 影响条数
- */
- @Override
- public <V> Long listLeftPush(String key, V value) {
- byte[] valBytes = this.serialize(value);
- byte[] keyBytes = this.serializeForString(key);
- return this.redisTemplate.execute(new RedisCallback<Long>() {
- @Override
- public Long doInRedis(RedisConnection connection) throws DataAccessException {
- return connection.lPush(keyBytes, valBytes);
- }
- });
- }
-
- /**
- * LIST 左读数据
- *
- * @param key 键
- * @param clazz 对象
- * @return 反系列化对象
- */
- @Override
- public <v> v listLeftPop(String key, Class<v> clazz) {
- final byte[] keyBytes = this.serializeForString(key);
- byte[] hGetBytes = this.redisTemplate.execute(connection -> connection.lPop(keyBytes), true);
- return this.deserialize(hGetBytes, clazz);
- }
-
- /**
- * LIST 右推数据
- *
- * @param key 键
- * @param value 对象
- * @return 影响条数
- */
- @Override
- public <V> Long lRightPush(String key, V value) {
- byte[] valBytes = this.serialize(value);
- byte[] keyBytes = this.serializeForString(key);
- return this.redisTemplate.execute(new RedisCallback<Long>() {
- @Override
- public Long doInRedis(RedisConnection connection) throws DataAccessException {
- return connection.rPush(keyBytes, valBytes);
- }
- });
- }
-
- /**
- * LIST 右读数据
- *
- * @param key 键
- * @param clazz 对象
- * @return 反系列化对象
- */
- @Override
- public <V> V lRightPop(String key, Class<V> clazz) {
- final byte[] keyBytes = this.serializeForString(key);
- byte[] hGetBytes = this.redisTemplate.execute(connection -> connection.rPop(keyBytes), true);
- return this.deserialize(hGetBytes, clazz);
- }
-
- @Override
- public Long length(String key) {
- final byte[] keyBytes = this.serializeForString(key);
- return this.redisTemplate.execute(connection -> connection.lLen(keyBytes), true);
- }
-
- public <V> List<V> getList(String key, Class<V> clazz) {
- int begin = 0;
- int end = Integer.MAX_VALUE;
- return this.getList(key, begin, end, clazz);
- }
-
- /**
- * 指定查询区间
- *
- * @param key
- * @param begin
- * @param end
- * @param clazz
- * @return
- */
- @Override
- public <V> List<V> getList(String key, final int begin, final int end, final Class<V> clazz) {
- List<V> valueList = new ArrayList<>();
- try {
- final byte[] keyBytes = this.serializeForString(key);
- List<byte[]> valueBytes = this.redisTemplate.execute(connection -> connection.lRange(keyBytes, begin, end), true);
- if (CollectionUtils.isEmpty(valueBytes)) {
- return valueList;
- }
- Iterator<byte[]> iterator = valueBytes.iterator();
- while (iterator.hasNext()) {
- byte[] next = iterator.next();
- valueList.add(deserialize(next, clazz));
- }
- } catch (Exception var6) {
- log.error(var6.getMessage(), var6);
- return valueList;
- }
- return valueList;
- }
-
- /**
- * HASH反系列化
- *
- * @param entries
- * @param clazz
- * @return
- */
- private <V> Map<String, V> deserializeMap(Map<byte[], byte[]> entries, Class<V> clazz) {
- if (entries == null) {
- return new HashMap<>(0);
- } else {
- Map<String, V> map = new LinkedHashMap<>(entries.size());
- Iterator<?> var4 = entries.entrySet().iterator();
-
- while (var4.hasNext()) {
- Map.Entry<byte[], byte[]> entry = (Map.Entry) var4.next();
- map.put(entry.getKey() == null ? null : new String(entry.getKey()), this.deserialize(entry.getValue(), clazz));
- }
-
- return map;
- }
- }
-
- /**
- * 序列Map key和value
- *
- * @param originalMap
- * @return
- * @throws Exception
- */
- private <V> Map<byte[], byte[]> serializeMap(Map<String, V> originalMap) {
- Map<byte[], byte[]> serializedMap = new HashMap<>();
-
- try {
- for (Map.Entry<String, V> entry : originalMap.entrySet()) {
- byte[] keyBytes = entry.getKey().getBytes();
- byte[] valueBytes;
-
- if (entry.getValue() instanceof String) {
- valueBytes = entry.getValue().toString().getBytes();
- } else if (entry.getValue() instanceof Integer) {
- valueBytes = Integer.toString((Integer) entry.getValue()).getBytes();
- } else if (entry.getValue() instanceof Long) {
- valueBytes = Long.toString((Long) entry.getValue()).getBytes();
- } else if (entry.getValue() instanceof Double) {
- valueBytes = Double.toString((Double) entry.getValue()).getBytes();
- } else if (entry.getValue() instanceof Float) {
- valueBytes = Float.toString((Float) entry.getValue()).getBytes();
- } else {
- if (entry.getValue() != null) {
- valueBytes = JSON.toJSONBytes(entry.getValue());
- } else {
- log.error("serializeMap -->Unsupported value type");
- continue;
- }
- }
- serializedMap.put(keyBytes, valueBytes);
- }
- } catch (Exception e) {
- log.error("serializeMap error ", e);
- }
-
- return serializedMap;
- }
-
- /**
- * 根据key查询hash类所有数据
- *
- * @param key
- * @param clazz
- * @return
- */
- @Override
- public <V> Map<String, V> hGetAll(String key, Class<V> clazz) {
- final byte[] keyBytes = this.serializeForString(key);
- if (this.hasKey(keyBytes)) {
- Map<byte[], byte[]> entries = this.redisTemplate.execute(connection -> connection.hGetAll(keyBytes), true);
- return this.deserializeMap(entries, clazz);
- } else {
- log.warn("没有找到【{}】的数据", key);
- return new HashMap<>();
- }
- }
-
- /**
- * 根据key-key精准查询hash类数据
- *
- * @param key redis主key
- * @param field 副键
- * @param clazz 对象类型
- * @return
- */
- @Override
- public <V> V hGet(String key, String field, Class<V> clazz) {
- V hashData = null;
- try {
- final byte[] keyBytes = this.serializeForString(key);
- if (this.hasKey(keyBytes)) {
- final byte[] fileIdBytes = this.serializeForString(field);
- byte[] hGetBytes = this.redisTemplate.execute(connection -> connection.hGet(keyBytes, fileIdBytes), true);
- if (hGetBytes != null) {
- hashData = deserialize(hGetBytes, clazz);
- }
- }
- } catch (Exception var6) {
- log.error(var6.getMessage(), var6);
- }
- return hashData;
- }
-
- @Override
- public <V> void hPut(String key, String field, V value) {
- try {
- final byte[] keyBytes = this.serializeForString(key);
- final byte[] hKeyBytes = this.serializeForString(field);
- final byte[] valBytes = this.serialize(value);
- this.redisTemplate.execute(new RedisCallback<Boolean>() {
- @Override
- public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
- return connection.hSet(keyBytes, hKeyBytes, valBytes);
- }
- });
- } catch (Exception e) {
- log.error("往hash存放数据失败【{}】【{}】,原因", key, field, e);
- }
- }
-
- @Override
- public <V> void hPutAll(String key, Map<String, V> value) {
- try {
- final byte[] keyBytes = this.serializeForString(key);
- Map<byte[], byte[]> serializeMap = this.serializeMap(value);
- if (!serializeMap.isEmpty()) {
- this.redisTemplate.execute(new RedisCallback<Object>() {
- @Override
- public Object doInRedis(RedisConnection connection) throws DataAccessException {
- connection.hMSet(keyBytes, serializeMap);
- return null;
- }
- });
- } else {
- log.warn("没有【{}】系列化后的数据,不执行存储", key);
- }
- } catch (Exception e) {
- log.error("往hash存放数据失败【{}】,原因", key, e);
- }
- }
-
- @Override
- public void hDel(String key, String hKey) {
- this.redisTemplate.opsForHash().delete(key, hKey);
- }
-
- /**
- * @param key key值
- * @return 是否存在
- * @Description: 是否存在当前key
- * @Author: chenzumao
- */
- public boolean hasKey(String key) {
- if (StringUtils.isBlank(key)) {
- return false;
- }
- return Boolean.TRUE.equals(this.redisTemplate.hasKey(key));
- }
-
- /**
- * @param keyBytes key值
- * @return 是否存在
- * @Description: 是否存在当前key
- * @Author: chenzumao
- */
- private boolean hasKey(final byte[] keyBytes) {
- if (null == keyBytes || keyBytes.length == 0) {
- return false;
- }
- return Boolean.TRUE.equals(this.redisTemplate.execute(connection -> connection.exists(keyBytes), true));
- }
-
- public Long delKey(String key) {
- log.debug("cache del key:{}", key);
- byte[] bytes = serializeForString(key);
- if (!hasKey(bytes)) {
- log.info("没有找到指定的key【{}】", key);
- return 0L;
- }
- return this.redisTemplate.execute(connection ->
- connection.del(bytes), true);
- }
- }
- package com.vanchan.sca.common.domian;
-
-
- import lombok.Data;
-
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import java.io.Serializable;
-
- //订单
- @Entity(name = "shop_order")
- @Data
- public class Order implements Serializable {
- /**
- * 订单id
- */
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long oid;
-
- /**
- * 用户id
- */
- private Integer uid;
-
- /**
- *用户名
- */
- private String username;
-
- /**
- *商品id
- */
- private Integer pid;
-
- /**
- *商品名称
- */
- private String pname;
-
- /**
- *商品单价
- */
- private Double pprice;
-
-
- /**
- *购买数量
- */
- private Integer number;
- }
- package com.vanchan.sca.test.order;
-
- import com.alibaba.fastjson.JSON;
- import com.vanchan.sca.common.domian.Order;
- import com.vanchan.sca.order.OrderApplication;
- import com.vanchan.sca.order.service.CommonRedisCacheService;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.collections4.CollectionUtils;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
- import java.util.*;
-
- /**
- * @author chenzumao
- * @Description TestRedisDemo
- * @since 2023/8/11 0:56
- */
-
- @RunWith(SpringJUnit4ClassRunner.class)
- @SpringBootTest(classes = {OrderApplication.class, TestRedisJsonDemo.class})
- @Slf4j
- public class TestRedisJsonDemo {
- @Autowired
- private CommonRedisCacheService commonRedisCacheService;
-
- @Autowired
- private RedisTemplate<String, Object> redisTemplate;
-
-
- public static final String ORDER_REDIS_KEY_MAP = "ORDER:OLD:KEY:MAP";
- public static final String ORDER_REDIS_OLD_KEY_MAP = "ORDER:OLD:KEY:MAP";
- public static final String ORDER_REDIS_NEW_KEY_MAP = "ORDER:NEW:KEY:MAP";
- public static final String ORDER_REDIS_NEW_KEY_STRING = "ORDER:KEY:STRING";
- public static final String ORDER_REDIS_LIST_DATA = "ORDER:LIST:KEY:DATA";
- public static final String ORDER_REDIS_SET_DATA = "ORDER:SET:KEY:DATA";
-
- /**
- * 原生redis存数据
- */
- @Test
- public void testPut() {
- Map<String, Object> orderMap = new HashMap<>();
- for (int i = 1; i < 4; i++) {
- Order order = new Order();
- order.setOid(Long.valueOf(i));
- order.setUid(i);
- order.setUsername("");
- order.setPid(i);
- order.setPname("");
- order.setPprice(0.0D);
- order.setNumber(0);
-
- orderMap.put(String.valueOf(i), order);
- }
- redisTemplate.opsForHash().putAll(ORDER_REDIS_OLD_KEY_MAP,orderMap);
-
- }
-
- /**
- * 批量推送HASH数据
- */
- @Test
- public void testPutAll() {
- Map<String, Object> orderMap = new HashMap<>();
- for (int i = 1; i < 4; i++) {
- Order order = new Order();
- order.setOid(Long.valueOf(i));
- order.setUid(i);
- order.setUsername("");
- order.setPid(i);
- order.setPname("");
- order.setPprice(0.0D);
- order.setNumber(0);
-
- orderMap.put(String.valueOf(i), order);
- }
-
- commonRedisCacheService.hPutAll(ORDER_REDIS_NEW_KEY_MAP, orderMap);
-
- Order order = new Order();
- order.setOid(Long.valueOf(7));
- order.setUid(7);
- order.setUsername("");
- order.setPid(7);
- order.setPname("");
- order.setPprice(0.0D);
- order.setNumber(0);
-
-
- commonRedisCacheService.hPut(ORDER_REDIS_NEW_KEY_MAP,"9", order);
-
-
- }
-
- /**
- * 查询hash数据
- */
- @Test
- public void testHashGetAll() {
-
- Map<String, Order> stringOrderMap = commonRedisCacheService.hGetAll(ORDER_REDIS_NEW_KEY_MAP, Order.class);
- if (stringOrderMap != null && !stringOrderMap.isEmpty()) {
- Iterator<Map.Entry<String, Order>> entryIterator = stringOrderMap.entrySet().iterator();
- while (entryIterator.hasNext()) {
- Map.Entry<String, Order> orderEntry = entryIterator.next();
- Order order = orderEntry.getValue();
- log.info("全量获取key【{}】当前值【{}】", orderEntry.getKey(), JSON.toJSONString(order));
- }
- } else {
- log.info("为空");
- }
-
- //hVals 命令获取hash 所有value值
- List<Order> list = commonRedisCacheService.hGetAllToList(ORDER_REDIS_NEW_KEY_MAP, Order.class);
- if(CollectionUtils.isNotEmpty(list)){
- log.info("hVals 命令获取hash 所有value值 获取到【{}】条,数据:{}",list.size(),JSON.toJSON(list));
- }else {
- log.info("hVals 命令获取hash 所有value值 为空");
- }
-
-
- Order order = commonRedisCacheService.hGet(ORDER_REDIS_NEW_KEY_MAP, "7", Order.class);
-
- log.info("单个查询接收到返回值:{}", (order != null ? JSON.toJSONString(order) : null));
-
-
- List<String> fields = new ArrayList<>();
- fields.add("3");
- fields.add("5");
- fields.add("9");
- List<Order> orderList = commonRedisCacheService.hGetAllToList(ORDER_REDIS_NEW_KEY_MAP, fields, Order.class);
-
- if(CollectionUtils.isNotEmpty(orderList)){
- log.info("指定field到【{}】条 值【{}】", orderList.size(), JSON.toJSONString(orderList));
- }
-
- }
-
- @Test
- public void testHGetOne() {
-
- }
-
- /**
- * 普通类型存取
- */
- @Test
- public void testPutAndGet() {
- for (int i = 1; i <= 2; i++) {
- Order order = new Order();
- order.setOid(Long.valueOf(i));
- order.setUid(i);
- order.setUsername("");
- order.setPid(9);
- order.setPname("");
- order.setPprice(0.0D);
- order.setNumber(0);
- String key = ORDER_REDIS_NEW_KEY_STRING + ":" + order.getUid();
- commonRedisCacheService.put(key, order);
- }
-
- log.info("插入成功");
- for (int i = 1; i <= 2; i++) {
- String key = ORDER_REDIS_NEW_KEY_STRING + ":" + i;
- Order o = commonRedisCacheService.get(key, Order.class);
- if (null != o) {
- log.info("key【{}】转化:{}", key, JSON.toJSONString(o));
- }
- }
-
-
- }
-
- /**
- * list类型存取
- */
- @Test
- public void testListPutAndGet() {
- for (int i = 1; i <= 2; i++) {
- Order order = new Order();
- order.setOid(Long.valueOf(i));
- order.setUid(i);
- order.setUsername("");
- order.setPid(9);
- order.setPname("");
- order.setPprice(0.0D);
- order.setNumber(0);
- //推送存储
- commonRedisCacheService.lRightPush(ORDER_REDIS_LIST_DATA,order);
- }
-
-
- log.info("插入成功");
- while (true){
- //左边开始读取
- try {
- Order order = commonRedisCacheService.listLeftPop(ORDER_REDIS_LIST_DATA, Order.class);
-
- if(null == order){
- break;
- }
-
- log.info("获取到:{}",JSON.toJSONString(order));
- } catch (Exception e) {
- log.error("异常信息:",e);
- }
- }
-
-
- }
-
- /**
- * set类型存取
- */
- @Test
- public void testSetPutAndGet() {
- for (int i = 1; i <= 2; i++) {
- Order order = new Order();
- order.setOid(Long.valueOf(i));
- order.setUid(i);
- order.setUsername("");
- order.setPid(9);
- order.setPname("");
- order.setPprice(0.0D);
- order.setNumber(0);
- //推送存储
- commonRedisCacheService.setAdd(ORDER_REDIS_SET_DATA,order);
- }
-
-
- log.info("插入成功");
- while (true){
- //左边开始读取
- try {
- Order order = commonRedisCacheService.setPop(ORDER_REDIS_SET_DATA, Order.class);
-
- if(null == order){
- break;
- }
-
- log.info("获取到:{}",JSON.toJSONString(order));
- } catch (Exception e) {
- log.error("异常信息:",e);
- }
- }
-
-
- }
- }
根据key获取所有
根据key获取value集合
根据key和field集合获取value集合
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。