spring-boot-starter-data-redis 翻译官方文档 8.7 - 8.10

本文介绍了Spring Data Redis中Partial Update的功能,允许不完全加载实体即可进行更新操作,并探讨了查询方法的使用,包括自动派生简单查询及利用RedisCallback进行更复杂的查询定制。

参考文档: https://docs.spring.io/spring-data/redis/docs/2.0.3.RELEASE/reference/html/

Redis中文教程: http://www.redis.net.cn/tutorial/3501.html


8.7. Persisting Partial Updates

在某些情况下,不需要加载和重写整个实体,只需在其中设置一个新值即可。 上次活动时间的会话时间戳可能是您只想更改一个属性的场景。 PartialUpdate允许定义对现有对象的设置和删除操作,同时负责更新实体本身的潜在到期时间以及索引结构。

PartialUpdate<Person> update = new PartialUpdate<Person>("e2c7dcee", Person.class)
  .set("firstname", "mat")                                                           
  .set("address.city", "emond's field")                                              
  .del("age");                                                                       

template.update(update);

update = new PartialUpdate<Person>("e2c7dcee", Person.class)
  .set("address", new Address("caemlyn", "andor"))                                   
  .set("attributes", singletonMap("eye-color", "grey"));                             

template.update(update);

update = new PartialUpdate<Person>("e2c7dcee", Person.class)
  .refreshTtl(true);                                                                 
  .set("expiration", 1000);

template.update(update);
1. Set the simple property firstname to mat.
2. Set the simple property address.city to emond’s field without having to pass in the entire object. 
This does not work when a custom conversion is registered.
3. Remove the property age.
4. Set complex property address.
5. Set a map/collection of values removes the previously existing map/collection and replaces the values with the given ones.
6. Automatically update the server expiration time when altering Time To Live.

 Time To Live

更新复杂对象以及映射/集合结构需要与Redis进一步交互以确定现有值,这意味着可能会发现重写整个实体可能会更快。

8.8. Queries and Query Methods

查询方法允许从方法名称自动派生简单的查找器查询。


Example 19. Sample Repository finder Method

public interface PersonRepository extends CrudRepository<Person, String> {

  List<Person> findByFirstname(String firstname);
}
请确保在查找器方法中使用的属性设置为索引。

Redis存储库的查询方法仅支持查询具有分页的实体和实体集合。

使用派生查询derived query 方法可能并不总是足以对要执行的查询建模。 RedisCallback提供了对索引结构的实际匹配或甚至自定义添加的更多控制。 它所需要的就是提供一个RedisCallback,它返回一个单独的或一组Iterable set的id值。

Example 20. Sample finder using RedisCallback

String user = //...

List<RedisSession> sessionsByUser = template.find(new RedisCallback<Set<byte[]>>() {

  public Set<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
    return connection
      .sMembers("sessions:securityContext.authentication.principal.username:" + user);
  }}, RedisSession.class);

以下概述了Redis支持的关键字以及包含该关键字的方法。

8.9. Redis Repositories running on Cluster

在群集的Redis环境中使用Redis repository support 很好。 有关ConnectionFactory配置详细信息,请参阅Redis群集 Redis Cluster 部分。 仍然需要考虑一些因素,因为默认的密钥分配会将实体和二级索引 secondary indexes 分散到整个集群及其插槽 slots中。

当所有相关密钥映射到同一个插槽时,只能在服务器端处理像SINTER和SUNION这样的一些命令。 否则,计算必须在客户端完成。 因此将密钥空间keyspaces 固定到单个插槽slot,可以立即使用Redis服务器计算。

在使用Redis群集时,通过`@RedisHash(“{yourkeyspace}”)定义和固定密钥空间到特定的插槽。

8.10. CDI integration

Instances of the repository interfaces are usually created by a container, which Spring is the most natural choice when working with Spring Data. There’s sophisticated support to easily set up Spring to create bean instances. Spring Data Redis ships with a custom CDI extension that allows using the repository abstraction in CDI environments. The extension is part of the JAR so all you need to do to activate it is dropping the Spring Data Redis JAR into your classpath.

You can now set up the infrastructure by implementing a CDI Producer for the RedisConnectionFactory and RedisOperations:

存储库接口的实例通常由一个容器创建,当使用Spring Data时,Spring是最自然的选择。 有复杂的支持来轻松设置,Spring来创建bean实例。 Spring Data Redis附带一个自定义CDI扩展,允许在CDI环境中使用存储库抽象。 这个扩展是JAR的一部分,所以你需要做的就是将Spring Data Redis JAR放入你的类路径中。

您现在可以通过为RedisConnectionFactory和RedisOperations实施CDI Producer来设置基础架构:
class RedisOperationsProducer {


  @Produces
  RedisConnectionFactory redisConnectionFactory() {

    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(new RedisStandaloneConfiguration());
    jedisConnectionFactory.afterPropertiesSet();

    return jedisConnectionFactory;
  }

  void disposeRedisConnectionFactory(@Disposes RedisConnectionFactory redisConnectionFactory) throws Exception {

    if (redisConnectionFactory instanceof DisposableBean) {
      ((DisposableBean) redisConnectionFactory).destroy();
    }
  }

  @Produces
  @ApplicationScoped
  RedisOperations<byte[], byte[]> redisOperationsProducer(RedisConnectionFactory redisConnectionFactory) {

    RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
    template.setConnectionFactory(redisConnectionFactory);
    template.afterPropertiesSet();

    return template;
  }

}
必要的设置可能因您运行的JavaEE环境而异。

Spring Data Redis CDI扩展将挑选所有可用作CDI bean的Repositories,并在容器请求存储库类型的bean时创建Spring Data repository的代理。 因此,获取Spring Data存储库的一个实例是声明一个@Injected属性的问题:
class RepositoryClient {

  @Inject
  PersonRepository repository;

  public void businessMethod() {
    List<Person> people = repository.findAll();
  }
}
Redis存储库需要RedisKeyValueAdapter和RedisKeyValueTemplate实例。 如果未找到提供的bean,则这些bean由Spring Data CDI扩展创建和管理。 但是,您可以提供自己的Bean来配置RedisKeyValueAdapter和RedisKeyValueTemplate的特定属性。





spring-boot-starter-data-redisredisson-spring-boot-starter均是Spring Boot里用于和Redis交互的依赖,不过它们有着不同的特点、使用场景和区别。 ### 依赖信息 - spring-boot-starter-data-redis:包含spring-data-redis,当前基本使用的就是它 [^1]。 - redisson-spring-boot-starter:依赖配置示例如下: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.17.7</version> <exclusions> <exclusion> <groupId>org.redisson</groupId> <artifactId>redisson-spring-data-26</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-data-21</artifactId> <version>3.17.7</version> </dependency> ``` ### 区别 - 功能层面: - spring-boot-starter-data-redis:提供基础的Redis操作,像对字符串、哈希、列表、集合等数据结构的操作;支持多种Redis客户端,例如Lettuce和Jedis。 - redisson-spring-boot-starter:在基础Redis操作之上,提供了分布式锁、分布式集合、分布式对象等分布式相关的功能,适用于复杂的分布式场景。 - 客户端层面: - spring-boot-starter-data-redis:默认采用Lettuce作为Redis客户端,也能配置成Jedis。 - redisson-spring-boot-starter:基于Redisson客户端,其具备更强大的分布式功能。 - 配置层面: - spring-boot-starter-data-redis:配置相对简单,一般在`application.properties`或者`application.yml`里配置Redis连接信息即可。 - redisson-spring-boot-starter:配置会复杂一些,需要配置Redisson的相关参数,例如分布式锁的超时时间等。 ### 使用场景 - spring-boot-starter-data-redis:适用于简单的缓存、数据存储等场景,例如将数据库查询结果缓存到Redis,以减轻数据库压力。示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.junit.jupiter.api.Test; public class RedisTest { @Autowired RedisTemplate redisTemplate; @Test void contextLoads1() { redisTemplate.opsForValue().set("ok", "测试ok1"); String ok = (String) redisTemplate.opsForValue().get("ok"); System.out.println(ok); } } ``` - redisson-spring-boot-starter:适用于复杂的分布式场景,例如分布式锁、分布式集合等。比如在分布式系统中,多个服务需要对同一资源进行操作时,可使用Redisson的分布式锁来保证数据的一致性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值