1. 程式人生 > 其它 >jedis.hmset()方法存<key, Map>太坑了啊,導致redis.clients.jedis.exceptions.JedisDataException: value sent to redis cannot be null異常問題

jedis.hmset()方法存<key, Map>太坑了啊,導致redis.clients.jedis.exceptions.JedisDataException: value sent to redis cannot be null異常問題

需要存的Map物件結構類似於:

Map result = new HashMap();

result.put("a", "a");
result.put("b", studentInfo);
result.put("c", null);

jedis.hmset("orgKey", result);

異常資訊:

[error] application - jedis error
redis.clients.jedis.exceptions.JedisDataException: value sent to redis cannot be null
	at redis.clients.util.SafeEncoder.encode(SafeEncoder.java:28)
	at redis.clients.jedis.Client.hmset(Client.java:184)
	at redis.clients.jedis.Jedis.hmset(Jedis.java:704)
	...

打斷點result也不為null,怎麼報錯不能為null呢,進入查看了原始碼方法才發現:

public void hmset(final String key, final Map<String, String> hash) {
    final Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(hash.size());
    for (final Entry<String, String> entry : hash.entrySet()) {
      bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue()));
    }
    hmset(SafeEncoder.encode(key), bhash);
  }

map的<key,value>的value不能為null

解決辦法(在此僅貼上我自己的方法,有更好的可以評論喲),換成mset()方法儲存結果,把Map轉為Json字串的形式儲存:

jedis.mset(orgKey, JSONObject.toJSON(result).toString());