我有一个对象:
@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 持久化数据要好得多。
例子如下:
注释实体
@RedisHash("persons") public class Person { @Id String id; String firstname; String lastname; Address address; }
创建Redis 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; } }
调用 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/