从零学spring boot-集成redis

添加依赖



    org.springframework.boot
    spring-boot-starter-data-redis
    
        
            redis.clients
            jedis
        
        
            io.lettuce
            lettuce-core
        
    


    redis.clients
    jedis



    com.fasterxml.jackson.core
    jackson-core
    2.9.5


    com.fasterxml.jackson.core
    jackson-databind
    2.9.5

添加配置

## 连接属性配置
spring.redis.host=
spring.redis.database=
spring.redis.port=
spring.redis.password=
spring.redis.timeout=

## 连接池配置
spring.redis.jedis.pool.max-active=
spring.redis.jedis.pool.max-idle=
spring.redis.jedis.pool.max-wait=
spring.redis.jedis.pool.min-idle=

上面的连接属性配置,spring data redis都已经做了默认的配置,如果连接数据和默认配置一样,则可以无需填写,下面的连接池配置虽然也做了默认配置,但是如果全部不填写,则会造成未使用连接池的情况

注入bean,解决序列化问题

redisTemplate默认使用的是JdkSerializationRedisSerializer,是不支持自定义对象的序列化的。

@Configuration
public class RedisConfig {


    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){
        //设置序列化
        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);
        // 配置redisTemplate
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

注入RedisTemplate进行redis操作

@Autowired
private RedisTemplate redisTemplate;

redisTemplate.opsForValue().set("key", "value");

你可能感兴趣的:(spring,boot,spring,redis)