zoukankan      html  css  js  c++  java
  • connect-mongo删除过期的session

    在使用express-session的时候,使用mongodb存储session,过期的session可以自动被删除,不需要代码中处理。

    通过查看源代码发现,在connect-mongo中使用设置索引的方式来自动删除过期的session。

    // 初始化connect-mongo的时候 autoRemove的的默认值native
    this.autoRemove = options.autoRemove || 'native'
    this.writeOperationOptions = options.writeOperationOptions || {}
    ....
    
    setAutoRemoveAsync() {
    	....
      switch (this.autoRemove) {
        case 'native':
          return this.collection.createIndex(
            { expires: 1 },
            Object.assign({ expireAfterSeconds: 0 }, this.writeOperationOptions)
          )
          ....
       }
       ....
     }
    

    在创建索引的时候增加参数 expireAfterSeconds,就可以做到自动删除过期文档;

    expireAfterSeconds的使用方法有两种:

    • 设定一条数据多久之后过期

    这种用法不需要计算什么时间过期,比较合适的使用场景是记录日志

    // 先创建一个索引,设置createdAt对应的时间一个小时之后过期
    db.logs.createIndex( { "a": 1 }, { expireAfterSeconds: 3600 } )
    
    // 插入一条数据  设置createdAt为插入数据的当前时间
    db.logs.insert( {
       "a": new Date(),
    } )
    
    • 设定一条数据什么时间过期

    connect-mongo中使用的就是这种方法

    // 比较明显的是expireAfterSeconds为0,那么插入数据的时候就需要指明具体过期日期
    db.logs.createIndex( { "a": 1 }, { expireAfterSeconds: 0 } )
    
    db.logs.insert( {
       "a": new Date('September 1, 2020 14:00:00'),
    } )
    
  • 相关阅读:
    01 输出字符串中字符的所有组合
    04 Redis主从同步
    03 Redis发布与订阅
    02 Redis防止入侵
    01 Redis基础
    MySQL索引优化 笔记
    SQL 基础语句整理
    jstl用法 简介
    type=file 上传图片限制 类型和尺寸 方法
    js 判断图片和视频是否加载成功
  • 原文地址:https://www.cnblogs.com/walkermag/p/13589319.html
Copyright © 2011-2022 走看看