网站seo基础优化,大连网站建设怎么做,静态页面加wordpress,义乌网站制作电话RedisTemplate 使用 pipeline 时需要注意的问题
RedisTemplate 使用 pipeline 进行批量 set 时#xff0c;需要把 key 和 value 都转为字节
1. 直接使用 getBytes() 转为字节#xff0c;在读取数据时#xff0c;会抛出以下序列化异常
//错误代码
protected void process(…RedisTemplate 使用 pipeline 时需要注意的问题
RedisTemplate 使用 pipeline 进行批量 set 时需要把 key 和 value 都转为字节
1. 直接使用 getBytes() 转为字节在读取数据时会抛出以下序列化异常
//错误代码
protected void process(ReconRedisContext reconRedisContext) {String key this.getLockKey(reconRedisContext);Pagination pagination this.queryReconData(reconRedisContext);if (ObjectUtils.isNotEmpty(pagination) CollectionUtils.isNotEmpty(pagination.getList())) {List? resList pagination.getList();redisTemplate.executePipelined(new RedisCallbackSet?() {Overridepublic Set? doInRedis(RedisConnection connection) throws DataAccessException {resList.stream().forEach(value - {connection.sAdd(key.getBytes(StandardCharsets.UTF_8), value.toString().getBytes(StandardCharsets.UTF_8));});return null;}});}}// 抛出序列化异常
org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unrecognized token value: was expecting (JSON String, Number, Array, Object or token null, true or false)2. 需要使用 RedisTemplate 已经设置的 Serializer 将key 和 value 序列化成byte数据代码如下
protected void process(ReconRedisContext reconRedisContext) {RedisSerializer keySerializer redisTemplate.getKeySerializer();RedisSerializer valueSerializer redisTemplate.getValueSerializer();String key this.getLockKey(reconRedisContext);Pagination pagination this.queryReconData(reconRedisContext);if (ObjectUtils.isNotEmpty(pagination) CollectionUtils.isNotEmpty(pagination.getList())) {List? resList pagination.getList();redisTemplate.executePipelined(new RedisCallbackSet?() {Overridepublic Set? doInRedis(RedisConnection connection) throws DataAccessException {resList.stream().forEach(value - {connection.sAdd(keySerializer.serialize(key), valueSerializer.serialize(value));});return null;}});}}3. 异常原因
// RedisTemplate 默认使用 DefaultSetOperations 存放数据的源码如下
public Long add(K key, V... values) {byte[] rawKey rawKey(key);byte[][] rawValues rawValues((Object[]) values);return execute(connection - connection.sAdd(rawKey, rawValues));
}byte[] rawKey(Object key) {Assert.notNull(key, non null key required);if (keySerializer() null key instanceof byte[]) {return (byte[]) key;}return keySerializer().serialize(key);
}byte[] rawValue(Object value) {if (valueSerializer() null value instanceof byte[]) {return (byte[]) value;}return valueSerializer().serialize(value);
}看源码RedisTemplate 也是把 key 和 value 都转为了字节但是使用了我们自己设置的 Serializer 所以我们在使用 pipeline 时也需要使用我们设置的 Serializer。
注意根据源码来看Redis 的其他数据结构使用 pipeline 时也会存在序列化的问题在代码编写的时候需要注意。 源自