描述
coding過程中,我們在使用redis進行存取Long或Byte型數(shù)據(jù)時衙解,發(fā)現(xiàn)存進去的Long數(shù)據(jù)阳柔,出來的卻是Integer數(shù)據(jù),當我們接收是使用Long或Byte取進行接收時就會報類型轉(zhuǎn)換錯誤蚓峦。
前提:當我們設(shè)置的redis的value序列化不是jdk自帶的序列化時才會報這個錯舌剂。
具體原理可以詳見鏈接:https://blog.51cto.com/u_3631118/3121370
代碼demo
redis序列化代碼
@Bean
public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setValueSerializer(getJackson2JsonRedisSerializer());
// 使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(getStringRedisSerializer());
template.setHashKeySerializer(getStringRedisSerializer());
template.setHashValueSerializer(getJackson2JsonRedisSerializer());
template.afterPropertiesSet();
RedisCacheUtils.setRedisTemplate(template);
return template;
}
錯誤使用
/**
* 新增
*/
private Long get(String no) {
String key = getKey(date);
Long value = RedisCacheUtils.getHash(key, no);
return value == null ? 0 :value;
}
/**
* 減少
*
* @param driverNo
* @param orderDate
* @return 操作后的數(shù)量
*/
private void hInc(String no) {
RedisCacheUtils.hIncrement(key, driverNo, -1L);
}
正確使用
/**
* 新增
*/
private Integer get(String no) {
String key = getKey(date);
Integer value = RedisCacheUtils.getHash(key, no);
return value == null ? 0 :value;
}
/**
* 減少
*
* @param driverNo
* @param orderDate
* @return 操作后的數(shù)量
*/
private void hInc(String no) {
RedisCacheUtils.hIncrement(key, driverNo, -1);
}
/**
* 減少
*
* @param driverNo
* @param orderDate
* @return 操作后的數(shù)量
*/
private void hInc(String no) {
RedisCacheUtils.hIncrement(key, driverNo, -1L);
}
public Long getTimestamp(String orderNo) {
return RedisCacheUtils.get(getKey(orderNo));
}
public void setTimestamp(String orderNo) {
RedisCacheUtils.set(getKey(orderNo), Instant.now().toEpochMilli(),1000, TimeUnit.MINUTES);
}