微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

springboot整合redis实例分析

这篇文章主要介绍了springboot整合redis实例分析的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springboot整合redis实例分析文章都会有所收获,下面我们一起来看看吧。

导入redis pom文件

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

编写redis配置

spring:
  redis:
    password:
    port: 6379
    host: localhost
    database: 0
    jedis:
      pool:
        ## 连接池最大连接数(使用负值表示没有限制)
        #spring.redis.pool.max-active=8
        max-active: 8
        ## 连接池最大阻塞等待时间(使用负值表示没有限制)
        #spring.redis.pool.max-wait=-1
        max-wait: -1
        ## 连接池中的最大空闲连接
        #spring.redis.pool.max-idle=8
        max-idle: 8
        ## 连接池中的最小空闲连接
        #spring.redis.pool.min-idle=0
        min-idle: 0
      ## 连接超时时间(毫秒)
    lettuce:
      shutdown-timeout: 0

编写springConfig文件

由于存储需要序列化,所以我们要配置redis的序列化方式,如果不配置的话key和value认使用的都是StringRedisSerializer,只能用来存储String类型的数据,因此需要配置我们常用的类型。同时我们的Java实体类也要一定要继承Serializable接口

@Configuration
public class RedisConfig {

    @Bean
    public Redistemplate<String , Object> redistemplate(RedisConnectionFactory factory){
        Redistemplate<String, Object> template = new Redistemplate<>();
        template.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setobjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

测试redis

在这一步前,我们要确定所连接的redis服务已经开启

@Autowired
    private Redistemplate<String , Object> redistemplate;
@Test
    public void testSelect() throws sqlException {
        redistemplate.opsForValue().set("qqq",userMapper.findByUname("zengkaitian"));
        System.out.println("redis获取的:"+redistemplate.opsForValue().get("qqq"));
    }

测试结果

springboot整合redis实例分析

关于“springboot整合redis实例分析”这篇文章内容就介绍到这里,感谢各位的阅读!相信大家对“springboot整合redis实例分析”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程之家行业资讯频道。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐