下面的场景如何利用redis和mongo?
How to leverage redis and mongo in the following scenario?
每当 mongodb 中发生更改时,我正在使用更改流来使 Redis 缓存保持最新。每当数据库更改时,我都会分两步更新缓存:
- 清除缓存
- 从头开始加载数据
代码:
redisTemplate.delete(BINDATA);
redisTemplate.opsForHash().putAll(BINDATA, binDataItemMap);
问题是在产品中这个设置可能是危险的。由于 Redis 是单线程的,因此在多容器应用程序中,事件有可能以下列方式发生:
- 发生数据库更新
- redis中数据被清除
- 请求进来查询一个空的redis缓存
- 数据推送到redis
理想情况下应该这样:
- 发生数据库更新
- redis中数据被清除
- 数据推送到redis
- 请求进来,查询更新的redis缓存
清除和更新操作如何在redis中作为一个块发生?
Redis 支持一种transactions。这完全符合您的需求。
All the commands in a transaction are serialized and executed sequentially. It can never happen that a request issued by another client is served in the middle of the execution of a Redis transaction. This guarantees that the commands are executed as a single isolated operation.
A Redis transaction is entered using the MULTI
command. At this point the user can issue multiple commands. Instead of executing these commands, Redis will queue them. All the commands are executed once EXEC
is called.
伪代码:
> MULTI
OK
> redisTemplate.delete(BINDATA);
QUEUED
> redisTemplate.opsForHash().putAll(BINDATA, binDataItemMap);
QUEUED
> EXEC
每当 mongodb 中发生更改时,我正在使用更改流来使 Redis 缓存保持最新。每当数据库更改时,我都会分两步更新缓存:
- 清除缓存
- 从头开始加载数据
代码:
redisTemplate.delete(BINDATA);
redisTemplate.opsForHash().putAll(BINDATA, binDataItemMap);
问题是在产品中这个设置可能是危险的。由于 Redis 是单线程的,因此在多容器应用程序中,事件有可能以下列方式发生:
- 发生数据库更新
- redis中数据被清除
- 请求进来查询一个空的redis缓存
- 数据推送到redis
理想情况下应该这样:
- 发生数据库更新
- redis中数据被清除
- 数据推送到redis
- 请求进来,查询更新的redis缓存
清除和更新操作如何在redis中作为一个块发生?
Redis 支持一种transactions。这完全符合您的需求。
All the commands in a transaction are serialized and executed sequentially. It can never happen that a request issued by another client is served in the middle of the execution of a Redis transaction. This guarantees that the commands are executed as a single isolated operation.
A Redis transaction is entered using the
MULTI
command. At this point the user can issue multiple commands. Instead of executing these commands, Redis will queue them. All the commands are executed onceEXEC
is called.
伪代码:
> MULTI
OK
> redisTemplate.delete(BINDATA);
QUEUED
> redisTemplate.opsForHash().putAll(BINDATA, binDataItemMap);
QUEUED
> EXEC