Redis中使用RedisTemplate.set设置值后到客户端取不到值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ncuzengxiebo/article/details/82780359

一、问题出现原因

     1、出现问题代码:

     

package com.hubena.redis.redistemplate;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RedisConfiguration.class})
public class RedisTemplateTest {
	private static final Logger logger = LoggerFactory.getLogger(RedisTemplateTest.class);
	@Autowired
    RedisTemplate redisTemplate;
	
	
	@SuppressWarnings("unchecked")
	@Test
	public void testRedisTemplate() throws ClassNotFoundException {
		@SuppressWarnings("rawtypes")
		SessionCallback<Object> sessionCallback = new SessionCallback() {

			@Override
			public Object execute(RedisOperations operations) throws DataAccessException {
				int count = 0;
				while (count < 1000) {
					operations.opsForValue().set("keyTest", "valueTest" + count);
					count++;
					logger.error("count:{}", operations.opsForValue().get("keyTest"));
				}
				
				return null;
			}
		};
		redisTemplate.execute(sessionCallback);
//		List<RedisClientInfo> list = redisTemplate.getConnectionFactory().getConnection().getClientList();
//		for (RedisClientInfo redisClientInfo : list) {
//			logger.error("getDatabaseId:{}", redisClientInfo.getDatabaseId());
//		}
//		redisTemplate.opsForValue().set("keyTest", String.valueOf(88888888));
//		logger.error("redis_db:{}", ((Jedis)redisTemplate.getConnectionFactory().getConnection().getNativeConnection()).getDB());
	}
}

        2、运行完上一步之后在客户端获取键为“keyTest”的值:

          Redis客户端取keyTest值

        如上图,取到的值为nil即为null。为什么呢,因为Template中set值时会先调用序列化器将键和值都序列化为byte字节数组放入redis数据库中,在客户端除非get后的key为“keyTest”使用同样的序列化器序列化后的值,否则取不到zh值。

 

        3、Template的set方法代码如下,会先将key序列化:

	byte[] rawKey(Object key) {

		Assert.notNull(key, "non null key required");

		if (keySerializer() == null && key instanceof byte[]) {
			return (byte[]) key;
		}

		return keySerializer().serialize(key);
	}

 

展开阅读全文

没有更多推荐了,返回首页