spring-data-redis 2.0 的使用

栏目: Java · 发布时间: 6年前

内容简介:在使用Spring Boot2.x运行Redis时,发现百度不到顺手的文档,搞通后发现其实这个过程非常简单和简洁,觉得有必要拿出来分享一下。Spring Boot2.x 不再使用Jedis,换成了Lettuce。Lettuce是基于 Netty 实现的,所以性能更好。但是我看到很多文章居然在Spring Boot 2.x还在写Jedis的配置。依赖比较简单,spring-boot-starter-data-redis、commons-pool2 即可。

在使用Spring Boot2.x运行 Redis 时,发现百度不到顺手的文档,搞通后发现其实这个过程非常简单和简洁,觉得有必要拿出来分享一下。

Spring Boot2.x 不再使用Jedis,换成了Lettuce。Lettuce是基于 Netty 实现的,所以性能更好。但是我看到很多文章居然在Spring Boot 2.x还在写Jedis的配置。

依赖

依赖比较简单,spring-boot-starter-data-redis、commons-pool2 即可。

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


        <!--spring2.0集成redis所需common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

属性配置

在属性中配置Redis Server的访问地址、密码、数据库,并配置连接池的属性。

redis:
    #    reids的连接ip
    host: 127.0.0.1
    port: 6379
    password: helloworld
    
    # Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
    database: 0
    
    # 连接超时时间(毫秒)
    timeout: 10000ms
    
    #  redis client配置,使用lettuce
    lettuce:
      pool:
        # 连接池中的最小空闲连接 默认 0
        min-idle: 0
        # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
        max-wait: 1000ms
        # 连接池最大连接数(使用负值表示没有限制) 默认 8
        max-active: 8
        # 连接池中的最大空闲连接 默认 8
        max-idle: 8

注解配置

全局使能缓存

@EnableSwagger2          // 使用swagger api 功能
@EnableCaching           // 使用缓存
@SpringBootApplication
public class Starter {

    public static void main(String[] args) {
        SpringApplication.run(Starter.class, args);
    }
}

通过注解使用缓存,@Cacheable 将获取值存入缓存

/**
     * 基于id 获取用户信息
     */
    @Cacheable(value="user", key="#id", unless="#result == null")
    public UserDTO GetUserById(int id) {
        User userEntity = userMapper.getUserByID(id);
        if (userEntity == null){
            return null;
        }

        /* entity 转 DTO */
        UserDTO userDTO = new UserDTO();
        userDTO.setAge(userEntity.getAge());
        userDTO.setId(id);
        userDTO.setName(userEntity.getName());
        userDTO.setCreateTime(unixTime2String(userEntity.getCreateTime()));
        userDTO.setPhone(userEntity.getPhone());
        userDTO.setEmail(userEntity.getEmail());
        return userDTO;
    }

@CachePut 更新缓存

@CachePut(value = "user", key="#p0.id")
    public UserDTO updateUser(InputUserInfoDTO inputUserInfoDTO){
        userMapper.updateUser(inputUserInfoDTO.getId(), inputUserInfoDTO.getName(), inputUserInfoDTO.getAge());
        User userEntity = userMapper.getUserByID(inputUserInfoDTO.getId());/* entity 转 DTO */

        if (null == userEntity){
            return null;
        }
        UserDTO userDTO = new UserDTO();
        userDTO.setAge(userEntity.getAge());
        userDTO.setId(userEntity.getId());
        userDTO.setName(userEntity.getName());
        userDTO.setCreateTime(unixTime2String(userEntity.getCreateTime()));
        userDTO.setPhone(userEntity.getPhone());
        userDTO.setEmail(userEntity.getEmail());
        return userDTO;
    }

@CacheEvict 删除缓存

@CacheEvict(value = "user", key="#id")
    public void deleteUser(int id){
        userMapper.deleteUser(id);
    }

当然为了支持序列化,我的UserDTO得implements Serializable

@Data
public class UserDTO implements Serializable {
//public class UserDTO implements Serializable {
    private int id;
    private String name;
    private int age;
    private String createTime;
    private String phone;
    private String email;
}

至此缓存已经可以用起来了,不需要编写RedisConfig代码,有点小遗憾,直接去Redis查看数据,发现是乱码。这是因为我使用的是 Java 自带的序列化,如果要更换Redis序列化方法,就要重写RedisConfig了。

RedisConfig

这个配置也不复杂,使用Jackson2JsonRedisSerializer将对象转换为Json串,注意这里一定要使用ObjectMapper,否则再将json串反序列化为对象时会报。

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig extends CachingConfigurerSupport{

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);

        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                                            .entryTtl(Duration.ZERO)
                                            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                                            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                                            .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build();
        return cacheManager;
    }
}

以上所述就是小编给大家介绍的《spring-data-redis 2.0 的使用》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Web Designer's Idea Book, Vol. 2

The Web Designer's Idea Book, Vol. 2

Patrick McNeil / How / 2010-9-19 / USD 30.00

Web Design Inspiration at a Glance Volume 2 of The Web Designer's Idea Book includes more than 650 new websites arranged thematically, so you can easily find inspiration for your work. Auth......一起来看看 《The Web Designer's Idea Book, Vol. 2》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具