批量保存

先看看采坑的代码:

  1. public void saveHash(Map<String,String> map){
  2. String redisKey = "test";
  3. RedisCallback<Object> callback = redisConnection -> {
  4. //打开管道
  5. redisConnection.openPipeline();
  6. map.entrySet().stream().forEach(entry -> {
  7. //保存
  8. redisConnection.hSet(redisKey.getBytes(),entry.getKey().getBytes(),entry.getValue().getBytes());
  9. });
  10. //固定返回null
  11. return null;
  12. };
  13. //执行
  14. redisTemplate.executePipelined(callback);
  15. }

现在保存如下数据

{
  "1":"名称1",
    "2":"名称2",
  "3":"名称3"
}

运行完以后的redis里的数据是这样的:
image.png

报错

乍一看数据是没问题的,但是去取数据的时候就会报错。
image.png
后来我试了一下,好像就是带了中文的不可以,放入数字、字母都不会报错。估计是反序列化的时候编码出现了问题。至于为啥报这个错我暂时也不清楚。

然后我参考了一下不通过管道保存的hash表:

image.png
发现都有双引号。
所以,我改了一下批量保存的代码:

解决

public void saveHash(Map<String,String> map){
    String redisKey = "test";
    RedisCallback<Object> callback = redisConnection -> {
        //打开管道
        redisConnection.openPipeline();
        map.entrySet().stream().forEach(entry -> {
            //保存
             //拼接双引号
            String value = "\"" + entry.getValue() + "\"";
            redisConnection.hSet(redisKey.getBytes(),entry.getKey().getBytes(),value.getBytes());
        });
        //固定返回null
        return null;
    };
    //执行
    redisTemplate.executePipelined(callback);

解决了。。。