栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.net中使用Redis(一)

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.net中使用Redis(一)

前言

Redis 是完全开源的,遵守 BSD 协议,是一个高性能的 key-value 数据库。

Redis 与其他 key - value 缓存产品有以下三个特点:

Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
Redis支持数据的备份,即master-slave模式的数据备份。

最近项目中需要使用Redis,这里简单记录一下Redis的安装,以及如何在.NET中使用Redis。

安装redis

这里我是使用window安装redis,具体安装过程可以参考这个链接https://www.runoob.com/redis/redis-install.html
里面也有各种环境下的安装教程。

选择适用的第三方客户端

官网主要推荐的是# ServiceStack.Redis与StackExchange.Redis,不过 ServiceStack.Redis是收费的。所以当然选择免费的。

开始写个简单的项目

为了快速搭建,我选择简单建个winfrom项目来测试我要的

WinFrom创建一个redis项目

这里我使用的VS2015版本,.net Framework版本我选择4.5(ps:版本越高支持的第三方客户端StackExchange.Redis版本越高)

Nuget管理添加StackExchange.Redis

因为项目框架是4.5,所以这里选择1.2.6版本安装

写个RedisHelper.cs 帮助类
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;

/// 
/// Redis读写帮助类
/// 
public class RedisHelper
{
    private string RedisConnectionStr = ConfigurationManager.AppSettings["RedisConnectionStr"];
    private ConnectionMultiplexer redis { get; set; }
    private IDatabase db { get; set; }
    public RedisHelper()
    {
        redis = ConnectionMultiplexer.Connect(RedisConnectionStr);
        db = redis.GetDatabase();
    }
    #region string类型操作
    /// 
    /// set or update the value for string key 
    /// 
    /// 
    /// 
    /// 
    public bool SetStringValue(string key, string value)
    {
        return db.StringSet(key, value);
    }
    /// 
    /// 保存单个key value
    /// 
    /// Redis Key
    /// 保存的值
    /// 过期时间
    /// 
    public bool SetStringKey(string key, string value,int expireMinutes =0)
    {
        if (expireMinutes > 0)
        {
            return db.StringSet(key, value, TimeSpan.FromMinutes(expireMinutes));
        }
        else
            return db.StringSet(key, value);
    }
    /// 
    /// 保存一个对象
    /// 
    /// 
    /// 
    /// 
    /// 
    public bool SetStringKey(string key, T obj, int expireMinutes = 0)
    {
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        if (expireMinutes > 0)
        {
            return db.StringSet(key, json, TimeSpan.FromMinutes(expireMinutes));
        }
        else
            return db.StringSet(key, json);

    }
    /// 
    /// 获取一个key的对象
    /// 
    /// 
    /// 
    /// 
    public T GetStringKey(string key) where T : class
    {
        var result = db.StringGet(key);
        if (string.IsNullOrEmpty(result))
        {
            return null;
        }
        try
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject(result);
        }
        catch
        {
            return null;
        }
    }
    /// 
    /// get the value for string key 
    /// 
    /// 
    /// 
    public string GetStringValue(string key)
    {
        return db.StringGet(key);
    }

    /// 
    /// Delete the value for string key 
    /// 
    /// 
    /// 
    public bool DeleteStringKey(string key)
    {
        return db.KeyDelete(key);
    }
    #endregion

    #region 哈希类型操作
    /// 
    /// set or update the HashValue for string key 
    /// 
    /// 
    /// 
    /// 
    /// 
    public bool SetHashValue(string key, string hashkey, string value)
    {
        return db.HashSet(key, hashkey, value);
    }
    /// 
    /// set or update the HashValue for string key 
    /// 
    /// 
    /// 
    /// 
    /// defined class
    /// 
    public bool SetHashValue(String key, string hashkey, T t) where T : class
    {
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(t);
        return db.HashSet(key, hashkey, json);
    }
    /// 
    /// 保存一个集合
    /// 
    /// 
    /// Redis Key
    /// 数据集合
    /// 
    public void HashSet(string key, List list, Func getModelId)
    {
        List listHashEntry = new List();
        foreach (var item in list)
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(item);
            listHashEntry.Add(new HashEntry(getModelId(item), json));
        }
        db.HashSet(key, listHashEntry.ToArray());
    }
    /// 
    /// 获取hashkey所有的值
    /// 
    /// 
    /// 
    /// 
    public List HashGetAll(string key) where T : class
    {
        List result = new List();
        HashEntry[] arr = db.HashGetAll(key);
        foreach (var item in arr)
        {
            if (!item.Value.IsNullOrEmpty)
            {
               result.Add(Newtonsoft.Json.JsonConvert.DeserializeObject(item.Value));            
            }
        }
        return result;
    }
    /// 
    /// get the HashValue for string key  and hashkey
    /// 
    /// Represents a key that can be stored in redis
    /// 
    /// 
    public RedisValue GetHashValue(string key, string hashkey)
    {
        RedisValue result = db.HashGet(key, hashkey);
        return result;
    }
    /// 
    /// get the HashValue for string key  and hashkey
    /// 
    /// Represents a key that can be stored in redis
    /// 
    /// 
    public T GetHashValue(string key, string hashkey) where T : class
    {
        RedisValue result = db.HashGet(key, hashkey);
        if (string.IsNullOrEmpty(result))
        {
            return null;
        }
        T t = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
        return null;
    }
    /// 
    /// delete the HashValue for string key  and hashkey
    /// 
    /// 
    /// 
    /// 
    public bool DeleteHashValue(string key, string hashkey)
    {
        return db.HashDelete(key, hashkey);
    }
    #endregion
}

redis的地址配置放app.config文件



     
        
    
  
    
  

测试

我这边简单展示了获取、设置、删除的功能

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                textBox1.Text = "请填写键";
                return;
            }
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                textBox2.Text = "请填写值";
                return;
            }
            if (string.IsNullOrEmpty(textBox3.Text))
            {
                textBox3.Text = "请填写过期时间";
                return;
            }
            //设置
            RedisHelper redis = new RedisHelper();
            redis.SetStringKey(textBox1.Text, textBox2.Text, int.Parse(textBox3.Text));
            textBox4.Text = "添加成功";

        }


        private void button2_Click(object sender, EventArgs e)
        {
            RedisHelper redis = new RedisHelper();
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                var val = redis.GetStringValue(textBox1.Text);
                if (!string.IsNullOrEmpty(val))
                {
                    //读取
                    textBox2.Text = val;
                }
                else
                {
                    textBox4.Text = "已过期或不存在";
                }
            }
            else
            {
                textBox1.Text = "请填写键";
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            RedisHelper redis = new RedisHelper();
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                if (redis.DeleteStringKey(textBox1.Text))
                {
                    //读取
                    textBox4.Text = "删除成功!";
                }
                else
                {
                    textBox4.Text = "删除失败!";
                }
            }
            else
            {
                textBox1.Text = "请填写键";
            }
        }

1、设置

2、获取

3、删除

我这里都只是简单展示string的操作,其他数据类型的大家也都可以试试。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/910249.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号