zoukankan      html  css  js  c++  java
  • c# Redis操作类

    需要添加StackExchange.Redis.dll引用

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using log4net;
    using Newtonsoft.Json;
    using StackExchange.Redis;
    using System.Configuration;
    
    namespace PKTDataService
    {
        class RedisHelper
        {
            ILog log = log4net.LogManager.GetLogger("RedisHelper");
            public ConnectionMultiplexer connection_ = null;
            private string redis_host = "127.0.0.1:6379";
            private int SORTTIMEOUT = 7;
            public RedisHelper()
            {
                 int.TryParse( ConfigurationManager.AppSettings["DBSERVER"],out SORTTIMEOUT);
            }
            public RedisHelper(string host)
            {
                redis_host = host;
            }
            public bool connectRedis()
            {
                if (connection_ == null || !connection_.IsConnected)
                {
                    try
                    {
                        var options = ConfigurationOptions.Parse(redis_host);
                        options.AllowAdmin = true;
                        connection_ = ConnectionMultiplexer.Connect(options);
                         
                 
                    }
                    catch (StackExchange.Redis.RedisConnectionException ex)
                    {
                        log.Error(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                    }
                }
                return connection_ != null && connection_.IsConnected;
            }
    
            public void CloseRedis()
            {
                if (connection_ != null || connection_.IsConnected)
                {
                    try
                    {
                        connection_.CloseAsync();
                        connection_.Dispose();
    
                    }
                    catch (StackExchange.Redis.RedisConnectionException ex)
                    {
                        log.Error(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                    }
                }
              
            }
    
            public int multi_set_key(Dictionary<string, object> items , int timeout = 0)
            {
                int count = 0;
                if (connectRedis())
                {
                    int v = 0;
                    IDatabase db = connection_.GetDatabase();
                    var trans = db.CreateTransaction();
                    foreach (string key in items.Keys)
                    {
                        string val = "";
                        object obj = new object();
                        if(items.TryGetValue(key, out obj))
                        {
                            val = obj.ToString();
                        }
                        if (!db.KeyExists(key))
                        {
                            trans.StringSetAsync(key, val);
                            trans.KeyExpireAsync(key, new TimeSpan(SORTTIMEOUT, 0, 0));//设置过期时间为3天
                            //if(timeout > 0)
                            //{
                            //    trans.KeyExpireAsync(key, new TimeSpan(0 , 0 , timeout));
                            //}
                            count++;
                        }                    
                    }
                    trans.Execute();
                }
                return count;
            }
            public bool slide_key_int(string key , int param)
            {
                if (connectRedis())
                {
                    int v = 0;
                    IDatabase db = connection_.GetDatabase();
                    ITransaction trans = db.CreateTransaction();
                    RedisValue val = db.StringGet(key);
                    if (val.HasValue)
                    {                    
                        Int32.TryParse(val.ToString(), out v);                    
                    }
                    v += param;
                    db.StringSet(key, string.Format("{0}", v));
                    log.Debug("更新redis值: " + key + "     " + val);
                    return trans.Execute();
                }
                return false;
            }
            /// <summary>
            /// 删除并返回存储在键上的列表的最后一个元素。
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public string rpopQueue(string key)
            {
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
               
                    if (db.KeyExists(key))
                    {
                        RedisValue val = db.ListRightPop(key);
                        if (val.HasValue)
                        {
                            log.Debug("删除的"+key + "的值為:   " + val);
                            return val.ToString();
                        }
                    }
                    else
                    {
                      //  log.Debug("rpopQueue方法" + key + "不存在");
                    }
                }
                return null;
            }
            public int lpushQueue(string key , string value)
            {
                int result = 0;
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
                    RedisValue val = db.ListLeftPush(key, value);
                    if (val.IsInteger)
                    {
                       val.TryParse(out result);
                    }
                   
                }
                return result;
            }
    
            public bool lpushQueue2(string key, string value)
            {
                int result = 0;
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
                    if (db.KeyExists(key))
                    {
                        RedisValue val = db.ListLeftPush(key, value);
                        if (val.IsInteger)
                        {
                            val.TryParse(out result);
                        }
                        return true;
                    }
                    else
                    {
                        RedisValue val = db.ListLeftPush(key, value);
                        return true;
                        //log.Warn("lpushQueue方法" + key + "不存在");
                    }
                }
                return false;
            }
    
            public string rpoplpushQueue(string key)
            {
                if (connectRedis())
                {
                    string push_key = string.Format("{0}_BACKUP", key);
                    IDatabase db = connection_.GetDatabase();
                    if (db.KeyExists(key))
                    {
                        RedisValue val = db.ListRightPopLeftPush(key, push_key);
                        if (val.HasValue)
                        {
                            return val.ToString();
                        }
                    }
                    else
                    {
                    
                       // log.Debug("rpoplpushQueue方法" + key + "不存在");
                    }
                }
                return null;
            }
            public string get_key(string key)
            {
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
                    if (db.KeyExists(key))
                    {
                        RedisValue val = db.StringGet(key);
                        if (val.HasValue)
                        {
                            return val.ToString();
                        }
                    }
                }
                return "";
            }
            public string delete_key(string key)
            {
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
                    if (db.KeyExists(key))
                    {
                        db.KeyDelete(key);
                    }
                }
                return "";
            }
            public bool set_key(string key , string val)
            {
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
               
                    return db.StringSet(key , val);               
                }
                return false;
            }
            public bool KeyExpire(string key, string val, TimeSpan timeout)
            {
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
                    return db.StringSet(key, val, timeout);     
                     
                }
                return false;
            }
            public bool KeyExsit(string key)
            {
                if (connectRedis())
                { 
                    IDatabase db=connection_.GetDatabase();
                    return  db.KeyExists(key);
                }
                return false;
            }
    
            public string count_queue(string key)
            {
                if (connectRedis())
                {
                    IDatabase db = connection_.GetDatabase();
                    RedisValue val = db.ListLength(key);
                    if (val.IsInteger)
                    {
                        return val.ToString();
                    }
                }
                return null;
            }
    
            /// <summary>
            /// 清空redis
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public bool FlushDatabase()
            {
                int num = 0;
                bool result = false;
                while (true)
                {
                    try
                    {
                        if (connectRedis())
                        {
                            connection_.GetServer(redis_host).FlushDatabase();
                            result = true;
                            break;
                        }
                        if (num > 10)
                        {
                            result = false;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        num++;
                        log.Debug(ex.Message);
                    }
                }
                return result;
             
            }
        }
    }
  • 相关阅读:
    JAVA-throw new IOException报错unhandled exception:java.lang.Exception 2021年6月7日
    GIt保持远程 源仓库与Fork仓库同步--2017年6月13日
    Python的getattr()-2017年6月7日
    JavaScript学习-2017年5月18日
    Writing your first Django app--2017年5月9日
    M4-AC6 Oh,Trojan Again--2017年5月9日
    吴军硅谷来信
    【1】Prologue--A Game of Thrones--2017年4月8日
    M4-PC9 Read 10,000 Books,Travel 10,000 Miles--2017年5月8日
    资源分配图RAG的化简
  • 原文地址:https://www.cnblogs.com/liuruitao/p/9679867.html
Copyright © 2011-2022 走看看