登录

java - mongodb配合redis缓存有没有成熟的方案?

业务系统采用了Mongodb,现在想针对部分数据用redis进行缓存优化。
原来看到过一个mongoose-redis-cache:https://github.com/conancat/mongoose-red...,我理解它相当于建立一个查询语句和查询结果的键值对,但这种情况下,如果数据库业务改变后是无法同步到缓存的。想请教下各位有没有其他方案?

# Java
怪我咯怪我咯2140 天前448 次浏览

全部回复(3) 我要回复

  • 巴扎黑

    巴扎黑2017-04-17 17:37:48

    用 spring-data 很好。有 mongodb 的也有 redis 的,直接使用spring-data-jpa 操作mongodb 方便快捷。而且spring有缓存的注解cacheable,可以实现自动存入缓存。
    spring-data 地址

    回复
    0
  • 高洛峰

    高洛峰2017-04-17 17:37:48

    建议redis与mongo处理数据时分开。先从mongo中获取数据,在set到redis。你用的mongoose-redis-cache这个,感觉在以后的扩展性上会很差,bug定位也不易

    回复
    0
  • ringa_lee

    ringa_lee2017-04-17 17:37:48

    不太懂js,简单看了下你给的连接的代码:
    1.mongoose-redis-cache:相当于在mongo前面包了一层redis,就像你说的那样,会对查询语句进行cache,
    key = [prefix, collectionName, hash].join ':'
    使用prefix,collName和查询语句生成redis中的key,先是返回redis的查询结果;如果没有,去查mongo;mongo的查询结果返回首先set redis,并设置超时时间,然后调用callback;
    2.题主所说“mongoose-redis-cache 对语句进行cache,如果数据库业务改变后是无法同步到缓存的”,这种是不需要担心的;一个可用的cache 肯定会考虑到数据的有效性,一般是通过设置超时时间来设置的;在代码中也可以看到,回填redis的时候会设置超时时间。

        hash = crypto.createHash('md5')
          .update(JSON.stringify query)
          .update(JSON.stringify options)
          .update(JSON.stringify fields)
          .update(JSON.stringify populate)
          .digest('hex')
    
        key = [prefix, collectionName, hash].join ':'
    
        cb = (err, result) ->
          if err then return callback err
    
          if not result
            # If the key is not found in Redis, executes Mongoose original
            # exec() function and then cache the results in Redis
    
            for k, path of populate
              path.options ||= {}
              _.defaults path.options, cache: false
    
            mongoose.Query::_exec.call self, (err, docs) ->
              if err then return callback err
              str = JSON.stringify docs
              client.setex key, expires, str
              callback null, docs
          else
            # Key is found, yay! Return the baby!
            docs = JSON.parse(result)
            return callback null, docs
    
        client.get key, cb

    回复
    0
  • 取消回复发送