错误信息:

Exception in thread "main" java.lang.IllegalArgumentException: template not initialized; call afterPropertiesSet() before using it
    at org.springframework.util.Assert.isTrue(Assert.java:92)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:183)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169)
    at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:91)
    at org.springframework.data.redis.core.DefaultListOperations.rightPush(DefaultListOperations.java:184)
    at com.zbz.redis.client.RedisTemplateClient.main(RedisTemplateClient.java:41)
 

分析:

       从错误信息知,需要先调用afterPropertiesSet方法,此方法是应该是初始化参数和初始化工作。

代码:

public static RedisTemplate getRedisTemplate(JedisConnectionFactory connectionFactory){
        
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(connectionFactory);
        StringRedisSerializer serializer = new StringRedisSerializer();
        redisTemplate.setDefaultSerializer(serializer);
        redisTemplate.setKeySerializer(serializer);
        redisTemplate.setValueSerializer(serializer);
        
        /**必须执行这个函数,初始化RedisTemplate*/
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

转自 https://blog.csdn.net/zhangbeizhen18/article/details/85272094