springboot引入Redis及其使用案例

1.安装Redis服务器

http://www.runoob.com/redis/redis-install.html

2.Springboot项目引入依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

3.配置

spring:
  redis:
    host: 192.168.10.134
    port: 6379

  

由于Springboot-data-redis帮我们自动装载了RedisTemplate对象,所以我们无需注册该bean。但是,如果用默认的 RedisTemplate ,那么在序列化存到redis中就会发现,key 就变的“不正常”了。

比如,存之前key为"test" ,进入redis看,key就变成了"\xac\xed\x00\x05t\x00\x04test" 。这与RedisTemplate默认提供的序列化协议有关。为了使其更符合我们的需求,我们需要订制序

列化协议。这里我们选择Springboot自带的Jackson为序列化协议,需要新建一个配置类,具体配置如下:

@Configuration
public class RedisConfiguration {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

4.测试使用

 这里使用SpringRunner.class 是Spring环境进行测试:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EdApplication.class)
public class FenCiUtilText {
    @Autowired
    private RedisTemplate redisTemplate;
    //测试放入
    @Test
    public void testRedisSet() {
        try {
            redisTemplate.opsForValue().set("test","This is a Springboot-Redis test!");
        } catch (Exception e){
            System.out.println(e.toString());
        }

    }
    //测试拿出
    @Test
    public void testRedisGet() {
        try {
            String key="test";
            Boolean isHas = redisTemplate.hasKey(key);
            if (isHas){
                Object test = redisTemplate.opsForValue().get(key);
                System.out.println(test);
            }else {
                System.out.println("抱歉!不存在key值为"+key);
            }
        } catch (Exception e){
            System.out.println(e.toString());
        }
    }
}

  

  

 

 

posted @ 2020-05-13 12:42  余情呀  阅读(3395)  评论(0编辑  收藏  举报