2026/6/11 3:13:38
网站建设
项目流程
无锡网络公司无锡网站推广,怎样建网站买东西,洛阳做网站多少钱,德州成交型网站建设前言#最近在开发项目#xff0c;用到了redis作为缓存#xff0c;来提高系统访问速度和缓解系统压力#xff0c;提高用户响应和访问速度#xff0c;这里遇到几个问题做一下总结和整理快速配置#SpringBoot整合redis有专门的场景启动器整合起来还是非常方便的dependency用到了redis作为缓存来提高系统访问速度和缓解系统压力提高用户响应和访问速度这里遇到几个问题做一下总结和整理快速配置#SpringBoot整合redis有专门的场景启动器整合起来还是非常方便的dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-redis/artifactId /dependency如果使用redis连接池引入!-- redis连接池 -- dependency groupIdorg.apache.commons/groupId artifactIdcommons-pool2/artifactId /dependency集成配置文件#------------------redis缓存配置------------ # Redis数据库索引默认为 0 spring.redis.database1 # Redis服务器地址 spring.redis.host 127.0.0.1 # Redis服务器连接端口 spring.redis.port6379 # Redis 密码 spring.redis.password # 连接超时时间毫秒 spring.redis.timeout 5000 # redis连接池 # 连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle10 # 连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle 500 # 连接池最大连接数使用负值表示没有限制 spring.redis.lettuce.pool.max-active2000 # 连接池最大阻塞等待时间使用负值表示没有限制 spring.redis.lettuce.pool.max-wait10000JSON序列化#由于缓存数据默认使用的是jdk自带的序列化 二进制需要序列化的实体类继承Serializable接口。而且序列化后的内容在redis中看起来也不是很方便。\xAC\xED\x00\x05sr\x00Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\xDFGc\x9D\xD0\xC9\xB7\x02\x00\x01L\x00\x0Aexpirationt\x00\x10Ljava/util/Date;xr\x00Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\xE1\x0E\x0AcT\xD4^\x02\x00\x01L\x00\x05valuet\x00\x12Ljava/lang/String;xpt\x00$805a75f7-2ee2-4a27-a598-591bfa1cf17dsr\x00\x0Ejava.util.Datehj\x81\x01KYt\x19\x03\x00\x00xpw\x08\x00\x00\x01}y\x81\xDB\x9Ax于是萌生了需要将数据序列化成json的想法。jackson序列化#在使用spring-data-redis,默认情况下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializer这个类来做序列化,Jackson redis序列化是spring中自带的.我们使用jackson方式Bean ConditionalOnClass(RedisOperations.class) public RedisTemplateString, Object redisTemplate(RedisConnectionFactory factory) { RedisTemplateString, Object template new RedisTemplate(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializerObject jackson2JsonRedisSerializer new Jackson2JsonRedisSerializer(Object.class); //序列化包括类型描述 否则反向序列化实体会报错一律都为JsonObject ObjectMapper mapper new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(mapper); StringRedisSerializer stringRedisSerializer new StringRedisSerializer(); // key采用 String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的 key也采用 String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用 jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的 value序列化方式采用 jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }序列化后存储在redis后内容[ com.qhong.test.dependBean.Person, { age: 20, name: name0, iss: true } ][ java.util.ArrayList, [ [ com.qhong.test.dependBean.Person, { age: 20, name: name0, iss: true } ], [ com.qhong.test.dependBean.Person, { age: 21, name: name1, iss: true } ], [ com.qhong.test.dependBean.Person, { age: 22, name: name2, iss: true } ] ] ]上面的不是严格符合json格式规范,虽然比默认二进制好注意这里序列化json代类型 com.qhong.test.dependBean.Person 如果没有这个反序列化会报类型转换异常错误也就是代码中这一段必须设置我之前就是没有设置反序列化都是JsonObject必须自己转换类型否则会报错//序列化包括类型描述 否则反向序列化实体会报错一律都为JsonObject ObjectMapper mapper new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(mapper);Fastjson序列化#需要倒入Fastjson到依赖!-- JSON工具 -- dependency groupIdcom.alibaba/groupId artifactIdfastjson/artifactId version1.2.76/version /dependency实现RedisSerializer接口import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class FastJson2JsonRedisSerializerT implements RedisSerializerT { public static final Charset DEFAULT_CHARSET StandardCharsets.UTF_8; static { ParserConfig.getGlobalInstance().setAutoTypeSupport(true); } private final ClassT clazz; public FastJson2JsonRedisSerializer(ClassT clazz) { super(); this.clazz clazz; } /** * 序列化 */ Override public byte[] serialize(T t) throws SerializationException { if (null t) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } /** * 反序列化 */ Override public T deserialize(byte[] bytes) throws SerializationException { if (null bytes || bytes.length 0) { return null; } String str new String(bytes, DEFAULT_CHARSET); return (T) JSON.parseObject(str, clazz); } }配置redisTemplateimport org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; Configuration AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisCacheAutoConfiguration { Bean public RedisTemplateObject, Object redisTemplate(RedisConnectionFactory factory) { RedisTemplateObject, Object template new RedisTemplate(); template.setConnectionFactory(factory); FastJson2JsonRedisSerializerObject fastJsonRedisSerializer new FastJson2JsonRedisSerializer(Object.class); StringRedisSerializer stringRedisSerializer new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用fastJson template.setValueSerializer(fastJsonRedisSerializer); // hash的value序列化方式采用fastJson template.setHashValueSerializer(fastJsonRedisSerializer); template.afterPropertiesSet(); return template; } }注意这是一种方式自己实现RedisSerializer 序列化接口但是FastJson 1.2.36版本以后不需要自己实现RedisSerializer为我们提供序列化支持在com.alibaba.fastjson.support.spring中 有GenericFastJsonRedisSerializer和FastJsonRedisSerializer两个实现类 区别在于GenericFastJsonRedisSerializer 可以自动转换对象类型FastJsonRedisSerializer 需要自定义转换需要的类型。通常使用GenericFastJsonRedisSerializer 即可满足大部分场景如果你想定义特定类型专用的 RedisTemplate 可以使用 FastJsonRedisSerializer 来代替 GenericFastJsonRedisSerializer”FastJson github有对应问题描述lssues 我已入坑 刚开始一直使用FastJsonRedisSerializer****无法自动反向序列化序列化后存储在redis后内容{ type: com.qhong.test.dependBean.Person, age: 20, iss: true, name: name0 }[ { type: com.qhong.test.dependBean.Person, age: 20, iss: true, name: name0 }, { type: com.qhong.test.dependBean.Person, age: 21, iss: true, name: name1 }, { type: com.qhong.test.dependBean.Person, age: 22, iss: true, name: name2 } ]正常情况是格式是正确的但是如果你存储内容出现set或者doubble类型会带上SetD类型描述如下会出现问题无法解析但是在程序里是可以反向序列化的分析参考对比#jdkSerializationRedisSerializer: 使用JDK提供的序列化功能。 优点是反序列化时不需要提供类型信息(class)但缺点是需要实现Serializable接口还有序列化后的结果非常庞大是JSON格式的5倍左右这样就会消耗redis服务器的大量内存。Jackson2JsonRedisSerializer 使用Jackson库将对象序列化为JSON字符串。优点是速度快序列化后的字符串短小精悍不需要实现Serializable接口。但缺点也非常致命那就是此类的构造函数中有一个类型参数必须提供要序列化对象的类型信息(.class对象)。 通过查看源代码发现其只在反序列化过程中用到了类型信息。FastJsonRedisSerializer 性能最优号称最快的json解析库但是反序列化后类字段顺序和原来实体类不一致发生改变在某些set,double字段情况下json格式不正确但是在程序可以解析更多问题参考#RedisTemplate序列化方式解读redis数据库操作#在整合了spring-boot-starter-data-redis后会自动帮我们注入redisTemplate 对象专门用来操作reids数据库的在reids中如果想用文件夹方式存储key的话类似这样我们只需要在存储使用使用::表示文件夹就可以了redisTemplate.opsForValue().set(userLoginCache::Kenx_6003783582be4c368af14daf3495559c, user);如果需要模糊查询key话使用*来表示 如获取所有keypublic static SetString getAllKey(String keys) { SetString key redisTemplate.keys(keys *); return key; }模糊批量删除/** * 删除缓存 * * param key 可以传一个值 或多个 */ public static void del(String... key) { if (key ! null key.length 0) { if (key.length 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(Arrays.asList(key)); } } }public static void delByPrefix(String key) { if (key ! null) { SetString keys redisTemplate.keys(key *); redisTemplate.delete(keys); } } public static void delBySuffix(String key) { if (key ! null) { SetString keys redisTemplate.keys(* key); redisTemplate.delete(keys); } } public static void clean(){ SetString keys redisTemplate.keys(*); redisTemplate.delete(keys); }因为使用很频繁所以我写成工具库RedisUtil 通过静态方法方式去调用就可以了基本上包含工作中用到的所有方法 这里附上源码package cn.soboys.kmall.cache.utils; import cn.hutool.extra.spring.SpringUtil; import org.springframework.data.redis.core.RedisTemplate; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * 定义常用的 Redis操作 * * author kenx */ public class RedisUtil { private static final RedisTemplateString, Object redisTemplate SpringUtil.getBean(redisTemplate, RedisTemplate.class); /** * 指定缓存失效时间 * * param key 键 * param time 时间(秒) * return Boolean */ public static Boolean expire(String key, Long time) { try { if (time 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key获取过期时间 * * param key 键 不能为 null * return 时间(秒) 返回 0代表为永久有效 */ public static Long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断 key是否存在 * * param key 键 * return true 存在 false不存在 */ public static Boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * * param key 可以传一个值 或多个 */ public static void del(String... key) { if (key ! null key.length 0) { if (key.length 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(Arrays.asList(key)); } } } public static void delByPrefix(String key) { if (key ! null) { SetString keys redisTemplate.keys(key *); redisTemplate.delete(keys); } } public static void delBySuffix(String key) { if (key ! null) { SetString keys redisTemplate.keys(* key); redisTemplate.delete(keys); } } public static void clean(){ SetString keys redisTemplate.keys(*); redisTemplate.delete(keys); } /** * 普通缓存获取 * * param key 键 * return 值 */ public static Object get(String key) { return key null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * param key 键 * param value 值 * return true成功 false失败 */ public static Boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * * param key 键 * param value 值 * param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * return true成功 false 失败 */ public static Boolean set(String key, Object value, Long time) { try { if (time 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 递增 * * param key 键 * param delta 要增加几(大于0) * return Long */ public static Long incr(String key, Long delta) { if (delta 0) { throw new RuntimeException(递增因子必须大于0); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * param key 键 * param delta 要减少几 * return Long */ public static Long decr(String key, Long delta) { if (delta 0) { throw new RuntimeException(递减因子必须大于0); } return redisTemplate.opsForValue().increment(key, -delta); } /** * HashGet * * param key 键 不能为 null * param item 项 不能为 null * return 值 */ public static Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取 hashKey对应的所有键值 * * param key 键 * return 对应的多个键值 */ public static MapObject, Object hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * 获取 hashKey对应的所有键 * * param key 键 * return 对应的多个键 */ public static SetString hmgetKey(String key) { Map map redisTemplate.opsForHash().entries(key); return map.keySet(); } /** * HashSet * * param key 键 * param map 对应多个键值 * return true 成功 false 失败 */ public static Boolean hmset(String key, MapString, Object map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * * param key 键 * param map 对应多个键值 * param time 时间(秒) * return true成功 false失败 */ public static Boolean hmset(String key, MapString, Object map, Long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * param key 键 * param item 项 * param value 值 * return true 成功 false失败 */ public static Boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * param key 键 * param item 项 * param value 值 * param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * return true 成功 false失败 */ public static Boolean hset(String key, String item, Object value, Long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除hash表中的值 * * param key 键 不能为 null * param item 项 可以使多个不能为 null */ public static void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * param key 键 不能为 null * param item 项 不能为 null * return true 存在 false不存在 */ public static Boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * param key 键 * param item 项 * param by 要增加几(大于0) * return Double */ public static Double hincr(String key, String item, Double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * * param key 键 * param item 项 * param by 要减少记(小于0) * return Double */ public static Double hdecr(String key, String item, Double by) { return redisTemplate.opsForHash().increment(key, item, -by); } /** * 根据 key获取 Set中的所有值 * * param key 键 * return Set */ public static SetObject sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据value从一个set中查询,是否存在 * * param key 键 * param value 值 * return true 存在 false不存在 */ public static Boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将数据放入set缓存 * * param key 键 * param values 值 可以是多个 * return 成功个数 */ public static Long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0L; } } /** * 将set数据放入缓存 * * param key 键 * param time 时间(秒) * param values 值 可以是多个 * return 成功个数 */ public static Long sSetAndTime(String key, Long time, Object... values) { try { Long count redisTemplate.opsForSet().add(key, values); if (time 0) { expire(key, time); } return count; } catch (Exception e) { e.printStackTrace(); return 0L; } } /** * 获取set缓存的长度 * * param key 键 * return Long */ public static Long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0L; } } /** * 移除值为value的 * * param key 键 * param values 值 可以是多个 * return 移除的个数 */ public static Long setRemove(String key, Object... values) { try { return redisTemplate.opsForSet().remove(key, values); } catch (Exception e) { e.printStackTrace(); return 0L; } } /** * 获取list缓存的内容 * * param key 键 * param start 开始 * param end 结束 0 到 -1代表所有值 * return List */ public static ListObject lGet(String key, Long start, Long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的长度 * * param key 键 * return Long */ public static Long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0L; } } /** * 通过索引 获取list中的值 * * param key 键 * param index 索引 index0时 0 表头1 第二个元素依次类推 * index0时-1表尾-2倒数第二个元素依次类推 * return Object */ public static Object lGetIndex(String key, Long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * * param key 键 * param value 值 * return Boolean */ public static Boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * param key 键 * param value 值 * param time 时间(秒) * return Boolean */ public static Boolean lSet(String key, Object value, Long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * param key 键 * param value 值 * return Boolean */ public static Boolean lSet(String key, ListObject value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * param key 键 * param value 值 * param time 时间(秒) * return Boolean */ public static Boolean lSet(String key, ListObject value, Long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据索引修改list中的某条数据 * * param key 键 * param index 索引 * param value 值 * return Boolean */ public static Boolean lUpdateIndex(String key, Long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N个值为value * * param key 键 * param count 移除多少个 * param value 值 * return 移除的个数 */ public static Long lRemove(String key, Long count, Object value) { try { return redisTemplate.opsForList().remove(key, count, value); } catch (Exception e) { e.printStackTrace(); return 0L; } } public static SetString getAllKey(String keys) { SetString key redisTemplate.keys(keys *); return key; } }原文链接:https://www.cnblogs.com/kenx/p/15506722.html作者kenx