spring-data-redis整合jedis和Lettuce的使用

spring-data-redis是什么

官方地址:https://spring.io/projects/spring-data-redis#support

  • 提供了对RedisTemplate统一的api来操作数据库

  • 支持Redis的发布订阅

  • 支持Redis的哨兵和Redis集群

  • 支持基于Lettuce的响应是编程

  • 支持基于JDK,JSON,字符串,spring对象的数据序列化以及反序列化

  • 支持基于Redis的Jdkcollection实现

  • spring-data-redis是spring官方提供的一个可以操作redis的框架

  • spring-data-redis整合了jedis和lettuce

  • spring-data-redis使我们在使用使用springboot框架可以更好的去使用redis

lettuce是什么

  • lettuce是一个线程安全的redis客户端。提供同步,异步和reactive(?)的 APIs.。如果可以避开阻塞和事务型的操作比如BLPOP 和MULTI/EXEC,多个线程可以分享同一个连接。多个连接被NIO框架netty有效的管理。

  • lettuce是基于netty实现的,支持同步,异步,和响应式编程方式,并且是线程安全的,支持Redis的哨兵模式,集群和管道模式。

基本使用

springDataRedis中提供了RedisTemplate工具类。其中封装了各种对redis的操作,并且将不同的api封装到不同的类型中

实际操作

  1. 导入maven依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
  1. 编写redis数据库配置

spring.redis.host=172.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=100ms
  1. 操作

private static final ObjectMapper mapper=new ObjectMapper();   //序列化工具 
@Autowired
private StringRedisTemplate redisTemplate;
User user = new User("小华", "玩");
try {
    //序列化成字符串
    String s = mapper.writeValueAsString(user);
    redisTemplate.opsForValue().set("user",s);
    //反序列化成user对象
    User user1 = mapper.readValue(redisTemplate.opsForValue().get("user"), User.class);
    System.out.println(user1);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

注意点:

  • 序列化成字符串表示将创建的user对象序列化成字符串,然后存进redis中,在读取的时候进行一个反序列化成user对象,保证了redis中保存的都是字符串

  • spring-data-redis默认使用的是lettuce,如果想要使用jedis就需要引入jedis依赖

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值