在spring-data-redis-reactive
中,写操作返回 redis 执行结果,这使得链接操作符非常困难。以Redis In Action的第 1 章中的示例 reddit 为例。我尝试像这样重新实现:
@Service
public class ArticleService {
private final ReactiveStringRedisTemplate redisTemplate;
private final long voteScore = 432L;
public ArticleService(ReactiveStringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public Mono<Article> createArticle(Article article) {
long now = System.currentTimeMillis();
Map<String, String> newArticle = new HashMap<>();
newArticle.put("title", article.getTitle());
newArticle.put("link", article.getLink());
newArticle.put("poster", article.getPoster());
newArticle.put("time", String.valueOf(now));
newArticle.put("votes", "1");
return redisTemplate.opsForValue()
.increment("article:")
.doOnNext(id -> redisTemplate.opsForSet().add("voted:" + id.toString(), article.getPoster()).subscribe())
.doOnNext(id -> redisTemplate.expire("votes:" + id.toString(), Duration.ofDays(7)).subscribe())
.doOnNext(id -> redisTemplate.opsForHash().putAll("article:" + id.toString(), newArticle).subscribe())
.doOnNext(id -> redisTemplate.opsForZSet().add("score:", "article:" + id.toString(), now + voteScore).subscribe())
.doOnNext(id -> redisTemplate.opsForZSet().add("time:", "article:" + id.toString(), now).subscribe())
.map(id -> {
article.setId(id);
article.setVotes("1");
return article;
});
}
}
如您所见,我使用它doOnNext
来避免丢失返回的 id 值increment
,并且subscribe()
在每个中都有一个doOnNext
来确保每个 redis 操作都被执行。但我不认为这是推荐的方式。我认为应用程序应该尽量避免subscribe()
并主要关注链接流。
做许多redis写操作的正确方法是什么spring-data-redis-reactive
?