Spring Data + Redis 带自动递增键 [英] Spring Data + Redis with Auto increment Key

查看:54
本文介绍了Spring Data + Redis 带自动递增键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to do Spring data CRUD Operation with Redis but mainly I need to store the auto increment key in Redis.

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

I have tried the simple CRUD operation for SpringData with Redis but there is no auto increment key feature.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

如果你使用的是 spring 数据 redis 存储库,你可以使用 org.springframework.data.annotation.Id 注释该字段,其中值需要自动生成,并在其类上添加 @RedisHash 注释.

If you are using spring data redis repository, you can annotate the field with org.springframework.data.annotation.Id for which value needs to be auto generated and a @RedisHash annotation on its class.

@RedisHash("persons")
public class Person {

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

现在要真正拥有一个负责存储和检索的组件,您需要定义一个存储库接口.

To now actually have a component responsible for storage and retrieval you need to define a repository interface.

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 注入到您的组件中.

Given the setup above you can go on and inject PersonRepository into your components.

@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 在这种情况下,例如.人: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/

这篇关于Spring Data + Redis 带自动递增键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆