【问题标题】:Spring Data + Redis with Auto increment Key带有自动增量键的 Spring Data + Redis
【发布时间】:2017-09-06 14:25:14
【问题描述】:

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

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

我怎样才能做到这一点?

【问题讨论】:

    标签: redis spring-data


    【解决方案1】:

    如果您使用的是spring数据redis存储库,您可以使用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 哈希中,其键具有模式 keyspace:id 在这种情况下,例如。人员:5d67b7e1-8640-4475-beeb-c666fab4c0e5。
    2. 使用提供的 id 检索存储在 keyspace:id 中的对象。
    3. 计算在 Person 上由 @RedisHash 定义的键空间中可用的实体总数。
    4. 从 Redis 中删除给定对象的键。

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

    【讨论】:

    • 感谢您的回答...根据上面它会给我像 - 5d67b7e1-8640-4475-beeb-c666fab4c0e5 但我期望自动递增 ID 像 1,2,3,4 ...在 radis 中。您上面提到的 Id 似乎是唯一键而不是增量键。
    猜你喜欢
    • 2020-06-03
    • 2017-01-05
    • 1970-01-01
    • 2018-02-25
    • 2023-03-03
    • 1970-01-01
    • 2018-09-06
    • 2021-09-13
    相关资源
    最近更新 更多