Spring Boot 使用 Redis

Spring Boot提供了spring-boot-starter-data-redis这样一个Starter,通过加入这样一个依赖,会自动配置RedisConnectionFactory,默认是基于Lettuce的实现。然后会基于RedisConnectionFactory自动配置RedisTemplate和基于String操作的StringRedisTemplate。

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

默认连接的Redis主机是localhost,端口号是6379。可以通过spring.redis.host指定需要连接的主机,通过spring.redis.port指定需要连接的主机端口号。比如下面指定了需要连接的Redis主机地址是192.168.0.104,端口号是6378。

spring.redis.host=192.168.0.104
spring.redis.port=6378

接着就可以按照Spring Data Redis中使用RedisTemplate和StringRedisTemplate的用法进行Redis的基本操作了。下面的代码中通过StringRedisTemplate设置了key1为一个String类型的缓存,为其指定了值和缓存失效时间。key2为List类型的缓存,每次都从最左边存入一个值,一共存了10个,然后再从Redis中获取key2对应的值依次输出。

@Autowired
private StringRedisTemplate stringRedisTemplate;
public void basicOperation() {
    BoundValueOperations<String, String> boundValueOps = this.stringRedisTemplate.boundValueOps("key1");
    boundValueOps.set("test string value", 60, TimeUnit.MINUTES);
  
    BoundListOperations<String, String> boundListOps = this.stringRedisTemplate.boundListOps("key2");
    for (int i=0; i<10; i++) {
        boundListOps.leftPush("V_" + (i*10 + i+1));
    }
  
    List<String> list = boundListOps.range(0, boundListOps.size());
    list.forEach(System.out::println);
}

Redis中存放Key和Value也可以是Java对象,对象默认会被序列化后再写入到Redis,然后读取的时候会被反序列化。下面的代码就是往Redis中存入Java对象的示例,Key和Value都可以是对象。

@Autowired
private RedisTemplate<Object, Object> redisTemplate;
public void operForUser() {
    User user = new User();
    user.setId(1L);
    user.setUsername("zhangsan");
    user.setName("张三");
    ValueOperations<Object, Object> opsForValue = this.redisTemplate.opsForValue();
    opsForValue.set(user, user);
  
    Object object = opsForValue.get(user);
    System.out.println(object);
  
    System.out.println("================================================");
  
    opsForValue.set("user::" + user.getId(), user);
  
    object = opsForValue.get("user::" + user.getId());
    System.out.println(object);
  
}
@Data
public static class User implements Serializable {
    private static final long serialVersionUID = -1479529526911953462L;
    private Long id;
    private String username;
    private String name;
}

Spring Boot自动配置Redis会将相关配置属性绑定到org.springframework.boot.autoconfigure.data.redis.RedisProperties类,更多的配置信息可以参考该类的API文档或源代码,比如配置连接池信息,配置数据库索引等。

Reactive

如果需要基于Reactive编程,则可以添加spring-boot-starter-data-redis-reactive依赖,这样org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration自动配置类将会生效,它会为我们自动创建一个ReactiveRedisTemplate类型的bean。

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

之后就可以通过ReactiveRedisTemplate基于Reactive进行编程了。下面是一个简单的示例。

@Autowired
private ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate;
public void reactive() {
    ReactiveValueOperations<Object, Object> opsForValue = this.reactiveRedisTemplate.opsForValue();
    User user = new User();
    user.setId(1L);
    user.setUsername("zhangsan");
    user.setName("张三");
    String key = "user::" + user.getId();
    Mono<Boolean> mono = opsForValue.set(key, user);
    if (mono.block()) {
        Mono<Object> mono2 = opsForValue.get(key);
        mono2.blockOptional().ifPresent(System.out::println);
    }
  
    ReactiveListOperations<Object, Object> opsForList = this.reactiveRedisTemplate.opsForList();
    String listKey = "list1";
    opsForList.leftPushAll(listKey, "A", "B", "C", "D", "E").subscribe();
    Flux<Object> flux = opsForList.range(listKey, 0, 10);
    flux.subscribe(System.out::println);
}