Spring Data + Redis 带自动递增键

Har*_*hit 5 redis spring-data

我正在尝试使用 Redis 进行 Spring 数据 CRUD 操作,但主要是我需要将自动增量键存储在 Redis 中。

我已经尝试使用 Redis 对 SpringData 进行简单的 CRUD 操作,但没有自动递增键功能。

我怎样才能做到这一点?

Mon*_*mul 3

如果您使用的是 Spring Data Redis 存储库,则可以在org.springframework.data.annotation.Id需要自动生成值的字段及其@RedisHash类上添加注释。

@RedisHash("persons")
public class Person {

  @Id String id;
  String firstname;
  String lastname;
  Address address;
}
Run Code Online (Sandbox Code Playgroud)

现在实际上有一个负责存储和检索的组件,您需要定义一个存储库接口。

public interface PersonRepository extends CrudRepository<Person, String> {

}

@Configuration
@EnableRedisRepositories
public class ApplicationConfig {

  @Bean
  public RedisConnectionFactory connectionFactory() {
    return new JedisConnectionFactory();
  }

  @Bean
  public RedisTemplate<?, ?> redisTemplate() {

    RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
    return template;
  }
}
Run Code Online (Sandbox Code Playgroud)

根据上面的设置,您可以继续将 PersonRepository 注入到您的组件中。

@Autowired PersonRepository repo;

public void basicCrudOperations() {

  Person rand = new Person("rand", "al'thor");
  rand.setAddress(new Address("emond's field", "andor"));

  repo.save(rand);               //1                          

  repo.findOne(rand.getId());    //2                          

  repo.count();                  //3                          

  repo.delete(rand);             //4                          
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果当前值为 null,则生成新的 id,或者重用已设置的 id 值,并将 Person 类型的属性存储在 Redis 哈希中,键的键采用 keyspace:id 模式(在这种情况下,例如)。人员:5d67b7e1-8640-4475-beeb-c666fab4c0e5。
  2. 使用提供的 id 检索存储在 keyspace:id 中的对象。
  3. 计算由 @RedisHash on Person 定义的键空间 Person 中可用的实体总数。
  4. 从 Redis 中删除给定对象的键。

参考: http: //docs.spring.io/spring-data/redis/docs/current/reference/html/