Redis, session expiration, and reverse lookup

前端 未结 2 1153
迷失自我
迷失自我 2021-01-31 19:08

I\'m currently bulding a web app and would like to use Redis to store sessions. At login, the session is inserted into Redis with a corresponding user id, and expiration set at

2条回答
  •  广开言路
    2021-01-31 19:59

    In more recent versions of Redis (2.8.0 and up) Keyspace Notifications for expired events are supported. I.e. when a key with a TTL expires this event is triggered.

    This is what to subscribe to:

    '__keyevent@0__:expired'
    

    So subscribing to this event allows you to have a single index for all sessions and you can remove the key from the index when the key expires.

    Example:

    Use a sorted set as a secondary index with the uid as the weight:

    ZADD "idx-session-uid"  
    

    Search for sessionkeys for a specific user with:

    ZRANGEBYSCORE "idx-session-uid"  
    

    When a session is deleted or expired we do:

    ZREM "idx-session-uid" 
    

提交回复
热议问题