我永远喜欢惠惠
2021-02-17 20:48
采纳率: 66.7%
浏览 420
已采纳

JAVA连接Redis报空指针

/**
*RedisConfig.java
**/

@Configuration  //配置类
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }
/**
*RedisConnect.java
**/

public class RedisTest {

    //这一行报错:Exception in thread "main" java.lang.NullPointerException
    @Autowired
     private RedisTemplate<String,Object> template;

    public void test(){
        User user = new User();
        user.setName("你好");
        user.setNo(123456);
        template.opsForValue().set("redis", user);
        User redis = (User) template.opsForValue().get("redis");
        System.out.println(redis);

    }
}
/**
*Application.java
**/
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
        RedisTest redisTest = new RedisTest();
        redisTest.test();    //这里报错:Exception in thread "main" java.lang.NullPointerException
    }
}
<!-- maven中与之关联的包 -->

        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>6.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
报错信息

Exception in thread "main" java.lang.NullPointerException
	at security.test.RedisTest.test(RedisConnect.java:20)
	at security.Application.main(Application.java:15)

尝试过各种相关的方法,折腾了一下午,实在顶不住了。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题