在springboot中使用lettuce来连接redis

一.搭建一个项目

  1. 选中spring initializr
    在这里插入图片描述
  2. 设置好项目名和包名后next
    在这里插入图片描述
  3. 设置要用的jar包,然后next,finish
    在这里插入图片描述
    在这里插入图片描述

二.配置lettuce

  1. 在pom.xml文件添加依赖
 <!--默认使用的是lettuce-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--lettuce-连接池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
  1. 在src/main/resources下新建一个application.yml文件
    !!!!!!!!!!!!注意,不要把注释加进去
server:
  port: 8080
spring:
  redis:
    port: 6379
    password: 123456
    host: 192.168.80.228
    lettuce: 
      pool:
        max-active: 8 #连接池最大连接数,为负数则没有限制
        max-idle: 8 #连接池最大空闲连接
        min-idle: 0 #连接池最小空闲连接
        max-wait: 1000 #连接池最大阻塞等待时间,为负数则没有限制
      	shutdown-timeout: 100 #关闭超时时间
  1. 编写config
    在src/main/java下新建一个config.RedisConfig.java
    这里的序列化配置不知道为什么一直没有生效,试过很多方法了,搞不懂,如果有会的大佬,可以告诉我怎么回事啊。
package com.config

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    // 使用Jackson2JsonRedisSerialize 替换默认序列化
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //设置序列化
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

三.测试是否配置成功

  1. 在SpringbootLettuceApplicationTests中
@SpringBootTest
class SpringbootLettuceApplicationTests {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Test
    void contextLoads() {
        System.out.println(redisTemplate);
        redisTemplate.opsForValue().set("aaaa12","123");
    }
}

能够输出org.springframework.data.redis.core.RedisTemplate@3e28fee1
或能够写入数据到redis就是成功了

posted @ 2020-03-01 17:39  程序员徐小白  阅读(540)  评论(0)    收藏  举报