c# 操作redis

c# 操作redis

一、安装StackExchange.Redis
通过NuGet 安装 StackExchange.Redis。

二、字符串

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using StackExchange.Redis;

namespace RedisApp
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private string connstr = "127.0.0.1:6379"; // 1127.0.0.1:6379,password=xxx
        private ConnectionMultiplexer redis { get; set; }
        private IDatabase db { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public void redis_init()
        {
            redis = ConnectionMultiplexer.Connect(connstr);
            db = redis.GetDatabase();
        }

        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetStringValue(string key, string value)
        {
            return db.StringSet(key, value);
        }

        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiry">过期</param>
        /// <returns></returns>
        public bool SetStringValueExpiry(string key, string value, TimeSpan? expiry = default(TimeSpan?))
        {
            return db.StringSet(key, value, expiry);
        }

        /// <summary>
        /// 获取一个key的对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetStringValue(string key)
        {
            return db.StringGet(key);
        }

        /// <summary>
        /// 删除key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool DeleteStringKey(string key)
        {
            return db.KeyDelete(key);
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, EventArgs e)
        {
            // addkeyvalue里面的timespan 可以是用beginTime 和 endTime来计算,此例子里面固定为10分钟,仅供参考。
            TimeSpan span = DateTime.Now.AddMinutes(10) - DateTime.Now;

            
            SetStringValue("9001", "1000");

            SetStringValueExpiry("9002", "1002", span);

            SetStringValueExpiry("9003", "1003", TimeSpan.FromSeconds(30)); // 设置时间 30s后过期。

        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMain_Load(object sender, EventArgs e)
        {
            // 初始化
            redis_init();
        }
    }
}

 

三、对象

需要安装Newtonsoft.Json。

存对象(对象需要序列化转成字符串,再存进库中)。
取对象(反序列化)。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace RedisApp
{

    public partial class FormMain : Form
    {
        public class User
        {
            public string Name;
            public int Age;
            public double Height;
        }

        public FormMain()
        {
            InitializeComponent();
        }

        private string connstr = "127.0.0.1:6379"; // 1127.0.0.1:6379,password=xxx
        private ConnectionMultiplexer redis { get; set; }
        private IDatabase db { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public void redis_init()
        {
            redis = ConnectionMultiplexer.Connect(connstr);
            db = redis.GetDatabase();
        }

        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetStringValue(string key, string value)
        {
            return db.StringSet(key, value);
        }

        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiry">过期</param>
        /// <returns></returns>
        public bool SetStringValueExpiry(string key, string value, TimeSpan? expiry = default(TimeSpan?))
        {
            return db.StringSet(key, value, expiry);
        }

        /// <summary>
        /// 获取一个key的对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetStringValue(string key)
        {
            return db.StringGet(key);
        }

        /// <summary>
        /// 删除key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool DeleteStringKey(string key)
        {
            return db.KeyDelete(key);
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, EventArgs e)
        {
            // addkeyvalue里面的timespan 可以是用beginTime 和 endTime来计算,此例子里面固定为10分钟,仅供参考。
            TimeSpan span = DateTime.Now.AddMinutes(10) - DateTime.Now;

            SetStringValue("9001", "1000");

            SetStringValueExpiry("9002", "1002", span);

            SetStringValueExpiry("9003", "1003", TimeSpan.FromSeconds(30)); // 设置时间 30s后过期。

        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMain_Load(object sender, EventArgs e)
        {
            // 初始化
            redis_init();
        }

        /// <summary>
        /// 测试工具类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRedis_Click(object sender, EventArgs e)
        {
            RedisHelper redisHelper = new RedisHelper("127.0.0.1:6379"); // "127.0.0.1:6379,password=food
            string value = redisHelper.GetStringValue("9001");
            tbLine.Text = value;
        }

        /// <summary>
        /// 测试对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnJson_Click(object sender, EventArgs e)
        {
            //  创建对象
            User user = new User();
            user.Name = "jiang";
            user.Age = 16;
            user.Height = 1.73;

            string demojson = JsonConvert.SerializeObject(user); // 序列化
            SetStringValue("model", demojson);

            string model = GetStringValue("model");
            User user_new = new User();
            user_new = JsonConvert.DeserializeObject<User>(model); // 反序列化
            tbLine.Text = user_new.Name + " " + user_new.Age + " " + user_new.Height;
        }
    }
}

四、StringIncrement 增量、StringDecrement 减量(默认值同为1)

double increment = 0;
double decrement = 0;

for (int i = 0; i < 10; i++)
{
    increment = db.StringIncrement("StringIncrement", 1); // 增量 每次+1
}

for (int i = 0; i < 10; i++)
{
    decrement = db.StringDecrement("StringIncrement"); // 减量 每次-1
}

五、List

Redis 列表是简单的字符串列表,按照插入顺序排序。可以添加一个元素到列表的头部或者尾部。

for (int i = 0; i < 5; i++)
{
    db.ListRightPush("list", i); // 从底部插入数据
}

for (int i = 5; i < 10; i++)
{
    db.ListLeftPush("list", i); // 从顶部插入数据
}

//var length = db.ListLength("list"); // 长度 10

//var rightPop = db.ListRightPop("list"); // 从底部拿出数据
// var leftPop = db.ListLeftPop("list"); // 从顶部拿出数据
// var list = db.ListRange("list");

六、Hash(哈希)

Redis hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象。相对于将对象的每个字段存成单个 string类型。一个对象存储在 hash 类型中会占用更少的内存,并且可以更方便的存取整个对象。

            //  创建对象
            User user_jiang = new User();
            user_jiang.Name = "jiang";
            user_jiang.Age = 16;
            user_jiang.Height = 1.73;

            User user_hao = new User();
            user_hao.Name = "hao";
            user_hao.Age = 17;
            user_hao.Height = 1.82;

            string json_jiang = JsonConvert.SerializeObject(user_jiang); // 序列化
            string json_hao = JsonConvert.SerializeObject(user_hao); // 序列化
            db.HashSet("user", "jiang", json_jiang);
            db.HashSet("user", "howsky", json_hao);


            // 获取Model
            string hash_jiang = db.HashGet("user", "jiang");
            User user = new User();
            user = JsonConvert.DeserializeObject<User>(hash_jiang); // 反序列化

            // 获取List
            RedisValue[] values = db.HashValues("user"); // 获取所有value
            IList<User> list = new List<User>();
            foreach (var item in values)
            {
                User model = JsonConvert.DeserializeObject<User>(item);
                list.Add(model);
            }

 

发表回复

您的电子邮箱地址不会被公开。