Net中应用 Redis 扩展类
GIt地址:https://gitee.com/loogn/stackexchange-redis-typedextensions
1.stackexchange 类调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using StackExchange.Redis; namespace RedisTest
{ public class User
{
public int ID { get; set; }
public string Name { get; set; }
} class Program
{
static void Main(string[] args)
{
using (var conn = ConnectionMultiplexer.Connect("localhost:6379,password=Aa111111."))
{
var db = conn.GetDatabase();
//list
db.ListRightPush("users", new User { ID = , Name = "a" });
db.ListRightPush("users", new User { ID = , Name = "b" });
db.ListRightPush("users", new User { ID = , Name = "c" }); Console.WriteLine(db.ListLength(CacheKeys.users));
User[] users = db.ListRange<User>(CacheKeys.users, , );
foreach (var item in users)
{
Console.WriteLine("ID:{0},Name:{1}", item.ID, item.Name);
} //Hash
db.HashSet<User>(CacheKeys.HashKey, "", new User { ID = });
db.HashSet<User>(CacheKeys.HashKey, "", new User { ID = });
db.HashSet<User>(CacheKeys.HashKey, "", new User { ID = });
var user3 = db.HashGet<User>(CacheKeys.HashKey, "");
Console.WriteLine("ID:{0},Name:{1}", user3.ID, user3.Name); //Set
db.SetAdd<User>(CacheKeys.SetKey, new User { ID = , Name = "名称23" });
db.SetAdd<User>(CacheKeys.SetKey, new User { ID = , Name = "名称13" });
var userRandom = db.SetRandomMember<User>(CacheKeys.SetKey);
Console.WriteLine("ID:{0},Name:{1}", userRandom.ID, userRandom.Name); //SortedSet
db.SortedSetAdd(CacheKeys.SortedSetKey, new User { ID = , Name = "name1" }, );
db.SortedSetAdd(CacheKeys.SortedSetKey, new User { ID = , Name = "Log3" }, );
db.SortedSetAdd(CacheKeys.SortedSetKey, new User { ID = , Name = "Log2" }, );
db.SortedSetAdd(CacheKeys.SortedSetKey, new User { ID = -, Name = "Log-1" }, -);
var userArr = db.SortedSetRangeByScoreWithScores<User>(CacheKeys.SortedSetKey);
foreach (var item in userArr)
{
Console.WriteLine("ID:{0},Name:{1},score:{2}", item.Element.ID, item.Element.Name, item.Score);
}
}
}
}
}
2.ServiceStack.Redis来调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis; namespace Com.Redis
{
/// <summary>
/// 来源:http://blog.wx6.org/2013/349.htm
/// </summary>
public class RedisBase
{
private static string[] ReadWriteHosts = System.Configuration.ConfigurationSettings.AppSettings["readWriteHosts"].Split(new char[] { ';' });
private static string[] ReadOnlyHosts = System.Configuration.ConfigurationSettings.AppSettings["readOnlyHosts"].Split(new char[] { ';' }); #region -- 连接信息 --
public static PooledRedisClientManager prcm = CreateManager(ReadWriteHosts, ReadOnlyHosts); private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
{
// 支持读写分离,均衡负载
return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
{
MaxWritePoolSize = , // “写”链接池链接数
MaxReadPoolSize = , // “读”链接池链接数
AutoStart = true,
});
}
#endregion #region -- Item --
/// <summary>
/// 设置单体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="t"></param>
/// <param name="timeSpan"></param>
/// <returns></returns>
public static bool Item_Set<T>(string key, T t)
{
try
{
using (IRedisClient redis = prcm.GetClient())
{
return redis.Set<T>(key, t, new TimeSpan(, , ));
}
}
catch (Exception ex)
{
// LogInfo
}
return false;
} /// <summary>
/// 获取单体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T Item_Get<T>(string key) where T : class
{
using (IRedisClient redis = prcm.GetClient())
{
return redis.Get<T>(key);
}
} /// <summary>
/// 移除单体
/// </summary>
/// <param name="key"></param>
public static bool Item_Remove(string key)
{
using (IRedisClient redis = prcm.GetClient())
{
return redis.Remove(key);
}
} #endregion #region -- List -- public static void List_Add<T>(string key, T t)
{
using (IRedisClient redis = prcm.GetClient())
{
var redisTypedClient = redis.GetTypedClient<T>();
redisTypedClient.AddItemToList(redisTypedClient.Lists[key], t);
}
} public static bool List_Remove<T>(string key, T t)
{
using (IRedisClient redis = prcm.GetClient())
{
var redisTypedClient = redis.GetTypedClient<T>();
return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > ;
}
}
public static void List_RemoveAll<T>(string key)
{
using (IRedisClient redis = prcm.GetClient())
{
var redisTypedClient = redis.GetTypedClient<T>();
redisTypedClient.Lists[key].RemoveAll();
}
} public static int List_Count(string key)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
return redis.GetListCount(key);
}
} public static List<T> List_GetRange<T>(string key, int start, int count)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
var c = redis.GetTypedClient<T>();
return c.Lists[key].GetRange(start, start + count - );
}
} public static List<T> List_GetList<T>(string key)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
var c = redis.GetTypedClient<T>();
return c.Lists[key].GetRange(, c.Lists[key].Count);
}
} public static List<T> List_GetList<T>(string key, int pageIndex, int pageSize)
{
int start = pageSize * (pageIndex - );
return List_GetRange<T>(key, start, pageSize);
} /// <summary>
/// 设置缓存过期
/// </summary>
/// <param name="key"></param>
/// <param name="datetime"></param>
public static void List_SetExpire(string key, DateTime datetime)
{
using (IRedisClient redis = prcm.GetClient())
{
redis.ExpireEntryAt(key, datetime);
}
}
#endregion #region -- Set --
public static void Set_Add<T>(string key, T t)
{
using (IRedisClient redis = prcm.GetClient())
{
var redisTypedClient = redis.GetTypedClient<T>();
redisTypedClient.Sets[key].Add(t);
}
}
public static bool Set_Contains<T>(string key, T t)
{
using (IRedisClient redis = prcm.GetClient())
{
var redisTypedClient = redis.GetTypedClient<T>();
return redisTypedClient.Sets[key].Contains(t);
}
}
public static bool Set_Remove<T>(string key, T t)
{
using (IRedisClient redis = prcm.GetClient())
{
var redisTypedClient = redis.GetTypedClient<T>();
return redisTypedClient.Sets[key].Remove(t);
}
}
#endregion #region -- Hash --
/// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public static bool Hash_Exist<T>(string key, string dataKey)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
return redis.HashContainsEntry(key, dataKey);
}
} /// <summary>
/// 存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public static bool Hash_Set<T>(string key, string dataKey, T t)
{
using (IRedisClient redis = prcm.GetClient())
{
string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
return redis.SetEntryInHash(key, dataKey, value);
}
}
/// <summary>
/// 移除hash中的某值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public static bool Hash_Remove(string key, string dataKey)
{
using (IRedisClient redis = prcm.GetClient())
{
return redis.RemoveEntryFromHash(key, dataKey);
}
}
/// <summary>
/// 移除整个hash
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public static bool Hash_Remove(string key)
{
using (IRedisClient redis = prcm.GetClient())
{
return redis.Remove(key);
}
}
/// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public static T Hash_Get<T>(string key, string dataKey)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
string value = redis.GetValueFromHash(key, dataKey);
return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(value);
}
}
/// <summary>
/// 获取整个hash的数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static List<T> Hash_GetAll<T>(string key)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
var list = redis.GetHashValues(key);
if (list != null && list.Count > )
{
List<T> result = new List<T>();
foreach (var item in list)
{
var value = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
result.Add(value);
}
return result;
}
return null;
}
}
/// <summary>
/// 设置缓存过期
/// </summary>
/// <param name="key"></param>
/// <param name="datetime"></param>
public static void Hash_SetExpire(string key, DateTime datetime)
{
using (IRedisClient redis = prcm.GetClient())
{
redis.ExpireEntryAt(key, datetime);
}
}
#endregion #region -- SortedSet --
/// <summary>
/// 添加数据到 SortedSet
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="t"></param>
/// <param name="score"></param>
public static bool SortedSet_Add<T>(string key, T t, double score)
{
using (IRedisClient redis = prcm.GetClient())
{
string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
return redis.AddItemToSortedSet(key, value, score);
}
}
/// <summary>
/// 移除数据从SortedSet
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="t"></param>
/// <returns></returns>
public static bool SortedSet_Remove<T>(string key, T t)
{
using (IRedisClient redis = prcm.GetClient())
{
string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
return redis.RemoveItemFromSortedSet(key, value);
}
}
/// <summary>
/// 修剪SortedSet
/// </summary>
/// <param name="key"></param>
/// <param name="size">保留的条数</param>
/// <returns></returns>
public static int SortedSet_Trim(string key, int size)
{
using (IRedisClient redis = prcm.GetClient())
{
return redis.RemoveRangeFromSortedSet(key, size, );
}
}
/// <summary>
/// 获取SortedSet的长度
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static int SortedSet_Count(string key)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
return redis.GetSortedSetCount(key);
}
} /// <summary>
/// 获取SortedSet的分页数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public static List<T> SortedSet_GetList<T>(string key, int pageIndex, int pageSize)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
var list = redis.GetRangeFromSortedSet(key, (pageIndex - ) * pageSize, pageIndex * pageSize - );
if (list != null && list.Count > )
{
List<T> result = new List<T>();
foreach (var item in list)
{
var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
result.Add(data);
}
return result;
}
}
return null;
} /// <summary>
/// 获取SortedSet的全部数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public static List<T> SortedSet_GetListALL<T>(string key)
{
using (IRedisClient redis = prcm.GetReadOnlyClient())
{
var list = redis.GetRangeFromSortedSet(key, , );
if (list != null && list.Count > )
{
List<T> result = new List<T>();
foreach (var item in list)
{
var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
result.Add(data);
}
return result;
}
}
return null;
} /// <summary>
/// 设置缓存过期
/// </summary>
/// <param name="key"></param>
/// <param name="datetime"></param>
public static void SortedSet_SetExpire(string key, DateTime datetime)
{
using (IRedisClient redis = prcm.GetClient())
{
redis.ExpireEntryAt(key, datetime);
}
}
#endregion
}
}
参考:
1.分布式中使用Redis实现Session共享(一)
Net中应用 Redis 扩展类的更多相关文章
- java中的redis工具类
1.redis基础类 package com.qlchat.component.redis.template; import javax.annotation.PostConstruct; impor ...
- DRF (Django REST framework) 中的视图扩展类
2. 五个扩展类 1)ListModelMixin 列表视图扩展类,提供list(request, *args, **kwargs)方法快速实现列表视图,返回200状态码. 该Mixin的list方法 ...
- 重构SP5中声明自定义扩展类为API调用
展的自定义类方法想要被前端异步调用必须在方法中 1.首先类必须继承自 AppService 类 2.方法必须指定特性 [ActionDescription("名称","编 ...
- tp5 中使用自定义扩展类和函数
如果是要引用其它控制器里定义的方法参考:https://www.cnblogs.com/efyefy/p/8796014.html 如果在extend定义的类和函数默认是在全局命名空间下的 new \ ...
- tp中调用PHP系统扩展类
例如使用Redis扩展类: use Reids; $redis = new Redis();
- [ios]objective-c中Category类别(扩展类)专题总结
本文转载至 http://yul100887.blog.163.com/blog/static/20033613520126333344127/ objective-c类别的作用?通过类别的方式, ...
- 安装redis和php的redis扩展
一.安装Redis 在服务器上下载好最新的redis解压包后,解压 #tar -zxvf redis-3.2.0-tar-gz #cd redis-3.2.0-tar-gz #make (redis- ...
- php 7 windows redis 扩展
搜了一圈也没找到redis 对于 php 7 windows 扩展,最后还是在apache lounge论坛找到了php7全扩展包 本人把里面的扩展全进行了上传(下载见本文底部) 在这里主要讲讲 ph ...
- Homestead中PHP扩展无phpize难以安装redis扩展的问题及解决办法
这真是一个非常深的坑.homestead中自带很多版本的php.然而扩展中缺没有phpize,这个东西是php添加扩展需要的东西本人在laravel中需要用到Redis扩展.这个和laravel的pr ...
随机推荐
- Tensorboard简介
Tensorflow官方推出了可视化工具Tensorboard,可以帮助我们实现以上功能,它可以将模型训练过程中的各种数据汇总起来存在自定义的路径与日志文件中,然后在指定的web端可视化地展现这些信息 ...
- windows server配置ftp服务器以及外网访问
在Server2012打开 服务器管理器,选择 添加角色与功能,添加Web服务下的FTP服务器 安装后. 我们现在C盘创建一个名字为FTP的文件夹,里面创建一个ftp的文件,做测试用,如图 打开服务器 ...
- Oracle之SQL优化专题02-稳固SQL执行计划的方法
首先构建一个简单的测试用例来实际演示: create table emp as select * from scott.emp; create table dept as select * from ...
- c++基础:之封装
原创: 零灵柒 C/C++的编程教室 2月4日 什么是类 C++是什么?C++设计之初就是class with c,所以简单点说,C++就是带类的C,那么什么是类? 类,简单点说就是类型,在 ...
- shell基础:1.1脚本执行方式
echo 后边跟的东西有空格,那么需要加上单引号或双引号.!是有特殊含义的,用单引号原意. 尽管linux不区分文件的后缀,但还是要写上以便于区分. #!Bash 这行不是注释,也不能省略,他的 ...
- lsof命令简介
lsof命令简介: lsof(list open files)是一个列出当前系统打开文件的工具.在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件 ...
- 路径遍历:ZIP条目覆盖
程序在解压zip文件时,如果没有验证zip条目,攻击者可能对条目覆盖,从而造成路径遍历 例如:以下代码示例解压zip文件. static final int BUFFER = 512; / ...
- 发布网站配置文件和SSL
1.将cert下新建一个文件将所有证书文件放在新建的文件下 例如:cert/medcard 2.配置网站的.conf文件 <VirtualHost *:443> ServerName ww ...
- Mysql重连错误
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully rec ...
- caffe-ssd运行create_data.sh的时候报错:SSD from caffe.proto import caffe_pb2 ImportError: No module named caffe.proto
在用voc2007和voc2012的数据训练基于caffe的SSD模型的时候,我们需要将图片数据转换成lmdb格式,运行脚本文件是SSD源码里面提供的create_data.sh(具体位置在$CAFF ...