java - 在 Spring Boot 应用程序中使用 redis 创建存储库

标签 java spring spring-boot redis repository-pattern

我有一个对象:

@Data
@AllArgsConstructor
public class ResultGeoObjectDto {
   private String addressLine;
   private String location;
   private double latitude;
   private double longitude;
}

我创建了一个服务,它与我的对象和 Redis 一起工作:

@Service
public class RedisService {

private final RedisTemplate<String, List<ResultGeoObjectDto>> redisTemplate;

@Autowired
public RedisService(RedisTemplate<String, List<ResultGeoObjectDto>> redisTemplate) {
    this.redisTemplate = redisTemplate;
}

public void setValue(String key, List<ResultGeoObjectDto> value) {

    redisTemplate.opsForList().leftPush(key, value);
}

public List<ResultGeoObjectDto> getGeoObjectByKey(String key) {
    return redisTemplate.opsForList().range(key, -1, -1).get(0);
}

public boolean objectExistInRedisStore(String key) {
    return redisTemplate.hasKey(key);
}

这很好用,但许多示例使用了 Repository 模式。你能告诉我如何制作存储库吗?

例如here使用静态 key ,我让它动态形成。而且我还有一个对象列表,而不是一个。我不明白我需要如何做正确的架构。

最佳答案

使用 Redis Repository 非常简单,并且比使用 RedisTemplate 持久化数据要好得多。

例子如下:

  1. 注释实体

    @RedisHash("persons")
    public class Person {
        @Id String id;
        String firstname;
        String lastname;
        Address address;
    }
    
  2. 创建Redis Repository接口(interface)

    public interface PersonRepository extends CrudRepository<Person, String> {}
    
  3. 配置

    @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;
      }
    }
    
  4. 调用 CRUD 操作。

    @Autowired PersonRepository repo;
    public void basicCrudOperations() {
      Person rand = new Person("rand", "al'thor");
      rand.setAddress(new Address("emond's field", "andor"));
      repo.save(rand); ①
      repo.findOne(rand.getId()); ②
      repo.count(); ③
      repo.delete(rand); ④
    }
    

引用:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis.repositories

关于java - 在 Spring Boot 应用程序中使用 redis 创建存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997678/

相关文章:

java - 使用 DOM4J 更改 XML 属性的最佳方法是什么

java - Spring MVC 中需要 Model POJO 吗?

java - 将基于 Spring Boot 的应用程序部署到 WebLogic 时出现 IllegalArgumentException

java - 通过 spring rest 模板获取异常的堆栈跟踪

java - REST API 调用是否应该在存储库层上使用 @Repository 进行?

java - 使用集合时覆盖的规则

java - 在数组中选择随机元素并将其放在 JLabel 上

java - 启用不跟踪

java - UnitTesting Spring Boot 中 Unresolved 依赖关系

spring - 使用嵌套数组的投影创建 Spring 数据聚合查询