需要添加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; }
}
}

c# Redis操作类的更多相关文章

  1. php的redis 操作类,适用于单台或多台、多组redis服务器操作

    redis 操作类,包括单台或多台.多组redis服务器操作,适用于业务复杂.高性能要求的 php web 应用. redis.php: <?php /* redis 操作类,适用于单台或多台. ...

  2. 设计模式之PHP项目应用——单例模式设计Memcache和Redis操作类

    1 单例模式简单介绍 单例模式是一种经常使用的软件设计模式. 在它的核心结构中仅仅包括一个被称为单例类的特殊类. 通过单例模式能够保证系统中一个类仅仅有一个实例并且该实例易于外界訪问.从而方便对实例个 ...

  3. 封装一个redis操作类来操作hash格式

    最近项目要用redis,依然是基于tp3.2. 发现thinkphp3.2自带的缓存类并不好使用,就自己封装了一个 目前只支持hash格式,其他数据类型的操作后面用到的时候再补充 <?php / ...

  4. spring 的redis操作类RedisTemplate

    spring 集成的redis操作几乎都在RedisTemplate内了. 已spring boot为例, 再properties属性文件内配置好 redis的参数 spring.redis.host ...

  5. Java的redis 操作类-优化通用版本

    java操作redis多节点处理方式;http://blog.itpub.net/29254281/viewspace-1188644/首先maven引入依赖包 <dependency> ...

  6. 用C#封装的ServiceStack.redis操作类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. <记录> PHP Redis操作类

    namespace common\controller; class Redis { public $redisObj = null; //redis实例化时静态变量 static protected ...

  8. 实用Redis操作类

    <?php /** * ------------------------------------------ * 统一redis的配置与数据存储规范,便于扩展与修改 * # redis通常用于热 ...

  9. PHP redis操作类 个人总结

    <pre name="code" class="php"><span style="font-size:18px;"> ...

  10. 一个简单清晰的Redis操作类

    <?php /** * redis处理的二次封装 * */ class Redis{ private $_redis; private $_config; public function __c ...

随机推荐

  1. Linux中的nc测试端口是否开放

    nc测试端口是否开放 在Linux中有一个级强大的网络工具netcat,在默认情况下面都是没有安装的,现在介绍一下安装过程 其实安装很简单 一.安装使用 1.只需输入命令yum安装: [root@SZ ...

  2. Spring boot 学习 五:domain的定义

    一 public class City implements Serializable 实现了Sericalizable接口,只是一种标志.表示可以被序列化. java的ObjectOutputStr ...

  3. Camera Vision - video surveillance on C#

    转自:http://blog.csdn.net/xyz_lmn/article/details/6072897 http://www.codeproject.com/KB/audio-video/ca ...

  4. Java高并发(1)

    1.同步和异步的区别和联系: 所谓同步,可以理解为在执行完一个函数或方法之后,一直等待系统返回值或消息,这时程序是出于阻塞的,只有接收到 返回的值或消息后才往下执行其它的命令. 异步,执行完函数或方法 ...

  5. hadoop2.6.0中自定义分割符

    最近在学习hadoop,用的hadoop2.6.0 然后在学习编写mapreduce程序时,发现默认对文件的输入是采用每行进行分割,下面来分析下改变这个分割方式的办法: 来看看默认是怎样实现的:

  6. 【240】◀▶IEW-Unit05

    Unit 5 Education: Study Abroad 表格技巧讲解 1. Model1对应表格分析 This table shows the numbers of international ...

  7. iview之select选择框选中内容后有空格的问题

    导致原因: option组件格式化造成的.此处</Option>在另一行,只要和输出内容一行,就不会有空格了. <Select :label-in-value="true& ...

  8. plsql&nbsp;分页

     select * from (select rownum rn,ps.* from (select * from user_t) ps ) where rn>=1 and rn<=10 ...

  9. java之二叉树--未完待续

    参考http://how2j.cn/k/collection/collection-tree/476.html#nowhere 二叉树概念 二叉树由各种节点组成二叉树特点:每个节点都可以有左子节点,右 ...

  10. Codeforces Round #403 (Div. 2, based on Technocup 2017 Finals)【A,B,C】

    翻车!翻车! codeforces782A A题: 水. 代码: #include <bits/stdc++.h> using namespace std; typedef long lo ...