SpringBoot 添加Redis,编写测试类错误

想往SpringBoot项目中集成Redis的,就准备先编个测试类测试一下,结果遇到点问题。记录下

一、集成redis

1、pom文件

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

2、application.yml

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 3
    jedis:
      pool:
        max-active: 8
        max-wait: 10
        min-idle: 0
        max-idle: 8
    password:
    timeout: 20000

3、配置文件RedisConfig

2020.04.27:注意:这个配置不加的话,会导致使用redisTemplate存储到redis上的key变成 value也是一样

package com.jsyl.stfw.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 作者: Pagegle李
 * 版本:1.0
 **/
@Configuration
@EnableCaching//开启注解
public class RedisConfig {
//    @Bean
//    public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
//        CacheManager cacheManager = new RedisCacheManager(redisTemplate);
//        return cacheManager;
//        /*RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//        // 多个缓存的名称,目前只定义了一个
//        rcm.setCacheNames(Arrays.asList("thisredis"));
//        //设置缓存默认过期时间(秒)
//        rcm.setDefaultExpiration(600);
//        return rcm;*/
//    }

    // 以下两种redisTemplate自由根据场景选择
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

二、编写测试类

public class redis {
    @Resource
    RedisTemplate redisTemplate;
    @Test
    public void testRedis(){
        redisTemplate.opsForValue().set("example:", "测试");
        String toekn = (String) redisTemplate.opsForValue().get("example:");
        System.err.println("====="+toekn+"===");
    }
}

启动报空指针异常,原因是容器没有启动,单纯的测试是无法注入的,要在测试类加上注解

@RunWith(SpringRunner.class)
@SpringBootTest
public class redis {
    @Resource
    RedisTemplate redisTemplate;
    @Test
    public void testRedis(){
        redisTemplate.opsForValue().set("example:", "测试");
        String toekn = (String) redisTemplate.opsForValue().get("example:");
        System.err.println("====="+toekn+"===");
    }
}

通过启动spring容器来执行测试,但此时又报错:

java.lang.IllegalStateException:找不到@SpringBootconfiguration,需要在测试中使用@Contextconfiguration或@SpringBootTest(classes=…)

原因是测试的包名路径与分支不一致,当时图省事随意建了下测试类的包名。

改成一致跑起来就可以了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章