springboot自定義redis序列化類解決increment操作失敗的問題
一、問題
在使用方法redisTemplateDB0.opsForHash().increment(key, item, by)時報了這個錯
Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR hash value is not an integer
一般hash結(jié)構(gòu)都是采用JsonSerialize或JdkSerialize來對對象進行序列化,而有時我們不光想存對象,也會存一些簡單的值。increment操作不會反序列化而是直接對存儲的值進行操作,此時該值經(jīng)過Json或Jdk序列化后不能直接進行加減操作,因為不能轉(zhuǎn)換為對應(yīng)的類型如integer、double、long。
最簡單的辦法就是重寫JsonSerialize的serialize方法,加上一個判斷,如果是String類型,就直接返回String.getBytes(),對象還是走原來的序列化方式
二、解決方式
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.7.RELEASE</version>
</dependency>
<!-- 提供redis連接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.0</version>
</dependency>自定義序列化類
package com.yolo.yoloblog.framework.engine.serializer;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.IOUtils;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.cache.support.NullValue;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.io.IOException;
/**
* 自定義redis序列化方式
* 問題:
* increment操作不會反序列化而是直接對存儲的值進行操作,此時該值經(jīng)過Json或Jdk序列化后不能直接進行加減操作,因為不能轉(zhuǎn)換為對應(yīng)的類型如integer、double、long
* 解決方式:
* 最簡單的辦法就是重寫JsonSerialize的serialize方法,加上一個判斷,如果是String類型,就直接返回String.getBytes(),對象還是走原來的序列化方式
* 總結(jié):
* increment使用要避免和其他需要經(jīng)過序列化的操作混用
* @author hl
* @date 2022/4/24 9:36
*/
@Component
public class CustomerGenericJackson2JsonRedisSerializer implements RedisSerializer<Object> {
private final ObjectMapper mapper;
public CustomerGenericJackson2JsonRedisSerializer() {
this((String)null);
}
public CustomerGenericJackson2JsonRedisSerializer(@Nullable String classPropertyTypeName) {
this(new ObjectMapper());
registerNullValueSerializer(this.mapper, classPropertyTypeName);
if (StringUtils.hasText(classPropertyTypeName)) {
this.mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, classPropertyTypeName);
} else {
this.mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
}
}
public CustomerGenericJackson2JsonRedisSerializer(ObjectMapper mapper) {
Assert.notNull(mapper, "ObjectMapper must not be null!");
this.mapper = mapper;
}
public static void registerNullValueSerializer(ObjectMapper objectMapper, @Nullable String classPropertyTypeName) {
objectMapper.registerModule((new SimpleModule()).addSerializer(new CustomerGenericJackson2JsonRedisSerializer.NullValueSerializer(classPropertyTypeName)));
}
@Override
public byte[] serialize(Object object) throws SerializationException {
if (object == null){
return new byte[0];
}
if (object instanceof String){
return ((String) object).getBytes(IOUtils.UTF8);
}
try {
return JSON.toJSONBytes(object, SerializerFeature.WriteClassName);
}catch (Exception e){
throw new SerializationException("Could not serialize: " + e.getMessage(),e);
}
}
@Override
public Object deserialize(@Nullable byte[] source) throws SerializationException {
return this.deserialize(source, Object.class);
}
@Nullable
public <T> T deserialize(@Nullable byte[] source, Class<T> type) throws SerializationException {
Assert.notNull(type, "Deserialization type must not be null! Please provide Object.class to make use of Jackson2 default typing.");
if (ObjectUtil.isNull(source)) {
return null;
} else {
try {
return this.mapper.readValue(source, type);
} catch (Exception var4) {
throw new SerializationException("Could not read JSON: " + var4.getMessage(), var4);
}
}
}
private static class NullValueSerializer extends StdSerializer<NullValue> {
private static final long serialVersionUID = 1999052150548658808L;
private final String classIdentifier;
NullValueSerializer(@Nullable String classIdentifier) {
super(NullValue.class);
this.classIdentifier = StringUtils.hasText(classIdentifier) ? classIdentifier : "@class";
}
public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField(this.classIdentifier, NullValue.class.getName());
jgen.writeEndObject();
}
}
}
配置類
package com.yolo.yoloblog.configuration;
import com.yolo.yoloblog.framework.engine.serializer.CustomerGenericJackson2JsonRedisSerializer;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfiguration{
//配置redis的過期時間
private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
// private static final GenericJackson2JsonRedisSerializer JSON_SERIALIZER = new GenericJackson2JsonRedisSerializer();
@Autowired
private CustomerGenericJackson2JsonRedisSerializer customerGenericJackson2JsonRedisSerializer;
@Bean
public GenericObjectPoolConfig poolConfig(){
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
//控制一個pool可分配多少個jedis實例
poolConfig.setMaxTotal(500);
//最大空閑數(shù)
poolConfig.setMaxIdle(200);
//每次釋放連接的最大數(shù)目,默認是3
poolConfig.setNumTestsPerEvictionRun(1024);
//逐出掃描的時間間隔(毫秒) 如果為負數(shù),則不運行逐出線程, 默認-1
poolConfig.setTimeBetweenEvictionRunsMillis(30000);
//連接的最小空閑時間 默認1800000毫秒(30分鐘)
poolConfig.setMinEvictableIdleTimeMillis(-1);
poolConfig.setSoftMinEvictableIdleTimeMillis(10000);
//最大建立連接等待時間。如果超過此時間將接到異常。設(shè)為-1表示無限制。
poolConfig.setMaxWaitMillis(1500);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setTestOnReturn(false);
poolConfig.setJmxEnabled(true);
poolConfig.setBlockWhenExhausted(false);
return poolConfig;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setDatabase(0);
configuration.setHostName("127.0.0.1");
configuration.setPassword("123456");
configuration.setPort(6380);
return createRedisTemplate(creatFactory(configuration));
}
@Bean
public RedisTemplate<Object, Object> redisTemplateDB0() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setDatabase(0);
configuration.setHostName("127.0.0.1");
configuration.setPassword("123456");
configuration.setPort(6380);
return createRedisTemplate(creatFactory(configuration));
}
private RedisTemplate createRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory);
//key的序列方式
template.setKeySerializer(STRING_SERIALIZER);
//hashKey的序列方式
template.setHashKeySerializer(STRING_SERIALIZER);
//value的序列方式
template.setValueSerializer(customerGenericJackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(customerGenericJackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
private LettuceConnectionFactory creatFactory(RedisStandaloneConfiguration configuration){
LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
builder.poolConfig(poolConfig());
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(configuration, builder.build());
connectionFactory.afterPropertiesSet();
return connectionFactory;
}
}工具類
package com.yolo.yoloblog.util;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Resource
private RedisTemplate<Object, Object> redisTemplateDB0;
public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
this.redisTemplateDB0 = redisTemplate;
}
//=============================common============================
/**
* 指定緩存失效時間
* @param key 鍵
* @param time 時間(秒)
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplateDB0.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根據(jù)key 獲取過期時間
* @param key 鍵 不能為null
* @return 時間(秒) 返回0代表為永久有效
*/
public long getExpire(String key){
return redisTemplateDB0.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判斷key是否存在
* @param key 鍵
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplateDB0.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除緩存
* @param key 可以傳一個值 或多個
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplateDB0.delete(key[0]);
}else{
redisTemplateDB0.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通緩存獲取
* @param key 鍵
* @return 值
*/
public Object get(String key){
return key==null?null:redisTemplateDB0.opsForValue().get(key);
}
/**
* 普通緩存放入
* @param key 鍵
* @param value 值
* @return true成功 false失敗
*/
public boolean set(String key,Object value) {
try {
redisTemplateDB0.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通緩存放入并設(shè)置時間
* @param key 鍵
* @param value 值
* @param time 時間(秒) time要大于0 如果time小于等于0 將設(shè)置無限期
* @return true成功 false 失敗
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplateDB0.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
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("遞增因子必須大于0");
}
return redisTemplateDB0.opsForValue().increment(key, delta);
}
/**
* 遞減
* @param key 鍵
* @param delta 要減少幾(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("遞減因子必須大于0");
}
return redisTemplateDB0.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 鍵 不能為null
* @param item 項 不能為null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplateDB0.opsForHash().get(key, item);
}
/**
* 獲取hashKey對應(yīng)的所有鍵值
* @param key 鍵
* @return 對應(yīng)的多個鍵值
*/
public Map<Object,Object> hmget(String key){
return redisTemplateDB0.opsForHash().entries(key);
}
/**
* HashSet
* @param key 鍵
* @param map 對應(yīng)多個鍵值
* @return true 成功 false 失敗
*/
public boolean hmset(String key, Map<String,Object> map){
try {
redisTemplateDB0.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并設(shè)置時間
* @param key 鍵
* @param map 對應(yīng)多個鍵值
* @param time 時間(秒)
* @return true成功 false失敗
*/
public boolean hmset(String key, Map<String,Object> map, long time){
try {
redisTemplateDB0.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
* @param key 鍵
* @param item 項
* @param value 值
* @return true 成功 false失敗
*/
public boolean hset(String key,String item,Object value) {
try {
redisTemplateDB0.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
* @param key 鍵
* @param item 項
* @param value 值
* @param time 時間(秒) 注意:如果已存在的hash表有時間,這里將會替換原有的時間
* @return true 成功 false失敗
*/
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplateDB0.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 void hdel(String key, Object... item){
redisTemplateDB0.opsForHash().delete(key,item);
}
/**
* 判斷hash表中是否有該項的值
* @param key 鍵 不能為null
* @param item 項 不能為null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item){
return redisTemplateDB0.opsForHash().hasKey(key, item);
}
/**
* hash遞增 如果不存在,就會創(chuàng)建一個 并把新增后的值返回
* @param key 鍵
* @param item 項
* @param by 要增加幾(大于0)
* @return
*/
public long hincr(String key, String item,long by){
return redisTemplateDB0.opsForHash().increment(key, item, by);
}
/**
* hash遞減
* @param key 鍵
* @param item 項
* @param by 要減少記(小于0)
* @return
*/
public double hdecr(String key, String item,double by){
return redisTemplateDB0.opsForHash().increment(key, item,-by);
}
//============================set=============================
/**
* 根據(jù)key獲取Set中的所有值
* @param key 鍵
* @return
*/
public Set<Object> sGet(String key){
try {
return redisTemplateDB0.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根據(jù)value從一個set中查詢,是否存在
* @param key 鍵
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return redisTemplateDB0.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將數(shù)據(jù)放入set緩存
* @param key 鍵
* @param values 值 可以是多個
* @return 成功個數(shù)
*/
public long sSet(String key, Object...values) {
try {
return redisTemplateDB0.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 將set數(shù)據(jù)放入緩存
* @param key 鍵
* @param time 時間(秒)
* @param values 值 可以是多個
* @return 成功個數(shù)
*/
public long sSetAndTime(String key,long time,Object...values) {
try {
Long count = redisTemplateDB0.opsForSet().add(key, values);
if(time>0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 獲取set緩存的長度
* @param key 鍵
* @return
*/
public long sGetSetSize(String key){
try {
return redisTemplateDB0.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值為value的
* @param key 鍵
* @param values 值 可以是多個
* @return 移除的個數(shù)
*/
public long setRemove(String key, Object ...values) {
try {
Long count = redisTemplateDB0.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================
/**
* 獲取list緩存的內(nèi)容
* @param key 鍵
* @param start 開始
* @param end 結(jié)束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key,long start, long end){
try {
return redisTemplateDB0.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 獲取list緩存的長度
* @param key 鍵
* @return
*/
public long lGetListSize(String key){
try {
return redisTemplateDB0.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通過索引 獲取list中的值
* @param key 鍵
* @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數(shù)第二個元素,依次類推
* @return
*/
public Object lGetIndex(String key,long index){
try {
return redisTemplateDB0.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 將list放入緩存
* @param key 鍵
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplateDB0.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將list放入緩存
* @param key 鍵
* @param value 值
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplateDB0.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
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplateDB0.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將list放入緩存
* @param key 鍵
* @param value 值
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplateDB0.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根據(jù)索引修改list中的某條數(shù)據(jù)
* @param key 鍵
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index,Object value) {
try {
redisTemplateDB0.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N個值為value
* @param key 鍵
* @param count 移除多少個
* @param value 值
* @return 移除的個數(shù)
*/
public long lRemove(String key,long count,Object value) {
try {
Long remove = redisTemplateDB0.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java將json字符串轉(zhuǎn)換為數(shù)組的幾種方法
在Java開發(fā)中,經(jīng)常會遇到將json字符串轉(zhuǎn)換為數(shù)組的需求,本文主要介紹了Java將json字符串轉(zhuǎn)換為數(shù)組的幾種方法,具有一定的參考價值,感興趣的可以了解一下2024-01-01
MyBatis的注解使用、ORM層優(yōu)化方式(懶加載和緩存)
這篇文章主要介紹了MyBatis的注解使用、ORM層優(yōu)化方式(懶加載和緩存),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
Java was started but returned exit code=13問題解決案例詳解
這篇文章主要介紹了Java was started but returned exit code=13問題解決案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-09-09
詳解java中finalize的實現(xiàn)與相應(yīng)的執(zhí)行過程
在常規(guī)的java書籍中,即會描述 object的finalize方法是用于一些特殊的對象在回收之前再做一些掃尾的工作,但是并沒有說明此是如何實現(xiàn)的.本篇從java的角度(不涉及jvm以及c++),有需要的朋友們可以參考借鑒。2016-09-09
當(dāng)事務(wù)Transactional遇見異步線程出現(xiàn)的坑及解決
這篇文章主要介紹了當(dāng)事務(wù)Transactional遇見異步線程出現(xiàn)的坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

