使用自增键的Spring Data和Redis

7

我正尝试使用Spring Data和Redis进行CRUD操作,但主要需要在Redis中存储自增键。

我已经尝试了SpringData与Redis的简单CRUD操作,但没有自增键功能。

我该如何实现这个?

1个回答

3
如果您正在使用Spring Data Redis Repository,您可以在该字段上注释org.springframework.data.annotation.Id,以自动生成值,并在其类上添加@RedisHash注释。
@RedisHash("persons")
public class Person {

  @Id String id;
  String firstname;
  String lastname;
  Address address;
}

现在,如果想要一个负责存储和检索的组件,您需要定义一个仓库接口。

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;
  }
}

在上述设置的基础上,您可以将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                          
}
  1. 如果当前值为null,则生成一个新的id或重新使用已设置的id值,并将类型为Person的属性存储在Redis Hash中,键名为keyspace:id,在这种情况下为persons:5d67b7e1-8640-4475-beeb-c666fab4c0e5。
  2. 使用提供的id检索存储在keyspace:id中的对象。
  3. 计算由@RedisHash定义的keyspace persons内可用的实体总数。
  4. 从Redis中删除给定对象的key。

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


感谢您的回答...根据上述内容,它将给我一个像5d67b7e1-8640-4475-beeb-c666fab4c0e5这样的ID,但我期望的是在radis中自动递增的ID,例如1、2、3、4...。在这里,您提到的ID似乎是唯一键而不是递增键。 - Harshit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接