Spring Data Redis(Redis Repositories)
Redis Repositories
使用仓储可以实现Redis Hashs与领域对象无缝的转换和存储,应用自定义的映射策略和使用二级索引。
Redis的仓储需要至少Redis 2.8.0版本。
1. Usage
利用仓储的支持可以很轻松的访问存储在Redis 里的领域实体。
Example 5. Sample Person Entity
@RedisHash("persons") public class Person { @Id String id; String firstname; String lastname; Address address; }
这个是一个相当简单的领域对象。注意,它有一个注释为org.springframework.data.annotation.Id 的属性id ,其类型注释为@RedisHash 。这个两个注释构成了持久化该hash 的真正的key。
有@Id 注解的属性和被命名为id 的属性会被当作标识属性。有注释的属性比其他的更受欢迎。
Example 6. Basic Repository Interface To Persist Person Entities
public interface PersonRepository extends CrudRepository<Person, String> { }
当仓储继承CrudRepository 后就具有了基础的CRUD 和查询操作的功能。要把它们结合在一起还需要Spring 的配置。
Example 7. JavaConfig for Redis Repositories
@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 注入到我们的组件中。
Example 8. Access to Person Entities
@Autowired PersonRepository repo; public void basicCrudOperations() { Person rand = new Person("rand", "althor"); rand.setAddress(new Address("emonds field", "andor")); repo.save(rand); repo.findOne(rand.getId()); repo.count(); repo.delete(rand); }
将Person 的所有属性存储到Redis Hash中,如果id 为null 则生成一个新的或重用一个已经存在的,存储的key 的模式为keyspace:id ,如 persons:5d67b7e1-8640-4475-beeb-c666fab4c0e5 使用提供的id 可以检索存储为keyspace:id 对应的object 可以使用@RedisHash 提供的keyspace(如persons)来统计实体的总数 利用key 可以删除Redis 中存储的对应的对象。
上一篇:
IDEA上Java项目控制台中文乱码