索引
Redis对字段的索引是通过,在Set中存储数据实现的,需要在对数据的索引字段CRUD或数据过期时对应修改索引存储数据。
RedisRepositories提供了自动维护索引和根据索引查询的功能,只需要在Redis实体中的索引字段添加@Index注解
@RedisHash("persons")
public class Person {
@Id String id;
@Indexed String firstname;
String lastname;
Address address;
}
保存两个firstname为小明和小王的Person对象RedisRepositories将额外执行以下Redis操作
SADD persons:firstname:小明 e2c7dcee-b8cd-4424-883e-736ce564363e
SADD persons:firstname:小王 a9d4b3a0-50d3-4538-a2fc-f7fc2581ee56
persons:firstname:小明为keyspace:indexFieldName:indexFiledValue结构的数据
e2c7dcee-b8cd-4424-883e-736ce564363e为对象的id值
内联属性(对象属性的属性)同样可以使用@Indexed
SADD persons:address.city:tear e2c7dcee-b8cd-4424-883e-736ce564363e
查询
可在Repository接口中定义查询方法
public interface PersonRepository extends CrudRepository<Person, String> {
List<Person> findByFirstname(String firstname);
}
- 查询方法使用的属性必须被索引
- 只能返回实体集合或分页的实体集合
方法名中支持的关键词
| 关键词 | 样例 |
|---|---|
| And | findByLastnameAndFirstname |
| Or | findByLastnameOrFirstname |
| Is,Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals |
| Top,First | findFirst10ByFirstname,findTop5ByFirstname |
Redis Repositories的集群支持
Redis Repositories良好的支持了Redis集群。
默认情况下
| key | 类型 | 槽 | 节点 |
|---|---|---|---|
| persons:e2c7dcee-b8cd-4424-883e-736ce564363e | id for hash | 15171 | 127.0.0.1:7381 |
| persons:a9d4b3a0-50d3-4538-a2fc-f7fc2581ee56 | id for hash | 7373 | 127.0.0.1:7380 |
| persons:firstname:rand | index | 1700 | 127.0.0.1:7379 |
一些像SINTER、SUNION的命令只能在所有数据在一个槽中才能执行,通过keyspaces可以让数据存储在一个槽中。
| key | 类型 | 槽 | 节点 |
|---|---|---|---|
| {persons}:e2c7dcee-b8cd-4424-883e-736ce564363e | id for hash | 2399 | 127.0.0.1:7379 |
| {persons}:a9d4b3a0-50d3-4538-a2fc-f7fc2581ee56 | id for hash | 2399 | 127.0.0.1:7379 |
| {persons}:firstname:rand | index | 2399 | 127.0.0.1:7379 |
通过定义@RedisHash(“{yourkeyspace}”) 定义keyspaces在Redis集群中使用特定的槽
TTL
缓存过期设置,可对方法和属性添加@TimeToLive设置缓存过期时间
public class TimeToLiveOnProperty {
@Id
private String id;
@TimeToLive
private Long expiration;
}
public class TimeToLiveOnMethod {
@Id
private String id;
@TimeToLive
public long getTimeToLive() {
return new Random().nextLong();
}
}
Redis索引与查询实践
14万+

被折叠的 条评论
为什么被折叠?



