1
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

StackExchange.Redisで閲覧履歴を実装

開発メモ

StackExchange.Redisの使い方は下記参照
https://github.com/StackExchange/StackExchange.Redis

登録

        //RedisのDBを選択
        IDatabase db = RedisRepository.SelectCache(0);

        //キーを生成
        var key = "hoge";

        // スコア算出の為、Unixtimeを取得
        var unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
        // 経過秒数をスコアとして保存
        var score = (double)unixSeconds;

        //閲覧履歴の情報をソート済みセット型で登録
        db.SortedSetAdd(key, "りんご", score);

        //保持期間を設定する場合は下記(例:30日)
        db.KeyExpire(key, new TimeSpan(30, 0, 0, 0));

        //最大件数を設定する場合は下記
        var current = db.SortedSetRangeByScore(key);
        var maxCnt = 10;
        if (current.Count() > maxCnt)
        {
            //最下位のデータを削除
            db.SortedSetRemoveRangeByRank(key,0,0);
        }

取得

        //最新の閲覧順(スコアが高い順)に取得
        var list = db.SortedSetRangeByScore(key, order: Order.Descending);

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
1
Help us understand the problem. What are the problem?