1.设置redis编码,都转成String
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisTemplateConfig {
@Bean("redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(om);
// 值采用json序列化
redisTemplate.setValueSerializer(serializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
redisTemplate.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(serializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
2.如果之前没有设置编码,
那么redis存储的数据为:
会以\xAC\xED\x00\x05t\x00开头
可以使用转码类把乱码转成正常的字符。但还是有一些额外的字符,需要用正则来截取.就可以得到一个正常的json字符串
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class DecoderUtils {
private static final String pattern = "\\{\"skuName\"(.*)}";
public static String hex2UTF8(String hexStr) {
String s = hexStr.replaceAll("\\\\x", "%")
.replaceAll("%AC%ED%00%05t%00%15", "")
.replaceAll("%AC%ED%00%05t%00%07", "")
.replaceAll("%AC%ED%00%05t%00'", "")
.replaceAll("%AC%ED%00%05t%00", "")
.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
try {
return URLDecoder.decode(s, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
log.info("hex2UTF8 转换异常======>" + hexStr);
}
return null;
}
public static void main(String[] args) {
Pattern p = Pattern.compile(pattern);
String str = hex2UTF8("\\xAC\\xED\\x00\\x05t\\x00{\"skuName\":\"\\xE6\\xB5\\x8B\\xE8\\xAF\\x95\\xE6\\x98\\xAF\\xE5\\x90\\xA6\\xE9\\x9C\\x80\\xE8\\xA6\\x81\\xE8\\xB5\\x84\\xE8\\xB4\\xA8000000004\",\"specification\":\"S05\",\"spuId\":18090,\"skuId\":40229}");
if (StringUtils.isNotEmpty(str)) {
Matcher m = p.matcher(str);
if (m.find()) {
String jsonStr = m.group(0);
log.info(jsonStr);
}
}
}
}