Redis一些基本的操作
代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using ServiceStack.Redis;
- using System.Configuration;
- using ServiceStack.Redis.Generic;
- using Newtonsoft.Json;
- namespace Rongzi.BZone.Common.Util
- {
- public class RedisCommon
- {
- private static readonly Lazy<RedisCommon> _instance = new Lazy<RedisCommon>(() => new RedisCommon());
- private static readonly string redisUrl = ConfigurationManager.AppSettings["Redis_Server"];
- private static readonly string redisPort = ConfigurationManager.AppSettings["Redis_Port"];
- private RedisCommon()
- {
- }
- public static RedisCommon getInstance
- {
- get
- {
- return _instance.Value;
- }
- }
- public RedisClient getRedisClient()
- {
- return new RedisClient(redisUrl, int.Parse(redisPort));
- }
- #region string类型操作
- /// <summary>
- /// 根据key获取对应的对象T
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key"></param>
- /// <returns></returns>
- public T GetObj<T>(string key)
- {
- T result;
- try
- {
- using (var redis = this.getRedisClient())
- {
- result = redis.Get<T>(key);
- }
- }
- catch (Exception)
- {
- result = default(T);
- }
- return result;
- }
- /// <summary>
- /// 根据key存储T对象
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key"></param>
- /// <param name="val"></param>
- /// <param name="dateTime"></param>
- /// <returns></returns>
- public bool SetObj<T>(string key, T val, DateTime dateTime)
- {
- bool result = false;
- try
- {
- using (var redis = this.getRedisClient())
- {
- result = redis.Set<T>(key, val, dateTime);
- }
- }
- catch
- {
- result = false;
- }
- return result;
- }
- /// <summary>
- /// 根据key更新T
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key"></param>
- /// <param name="t"></param>
- /// <returns></returns>
- public bool UpdateObj<T>(string key, T t)
- {
- bool result = false;
- using (var redis = this.getRedisClient())
- {
- var value = JsonConvert.SerializeObject(t);
- result = redis.Set<string>(key, value);
- }
- return result;
- }
- /// <summary>
- /// 删除对应key的value
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public bool RemoveObj(string key)
- {
- bool result = false;
- using (var redis = this.getRedisClient())
- {
- result = redis.Remove(key);
- }
- return result;
- }
- #endregion
- #region hash类型操作
- /// <summary>
- /// 从hash表获取数据
- /// </summary>
- public T Get<T>(string hashId, string key)
- {
- using (var redis = this.getRedisClient())
- {
- string value = redis.GetValueFromHash(hashId, key);
- return JsonConvert.DeserializeObject<T>(value);
- }
- }
- /// <summary>
- /// 获取整个hash的数据
- /// </summary>
- public List<T> GetAll<T>(string hashId)
- {
- using (var redis = this.getRedisClient())
- {
- var result = new List<T>();
- var list = redis.GetHashValues(hashId);
- if (list != null && list.Count > )
- {
- list.ForEach(x =>
- {
- var value = JsonConvert.DeserializeObject<T>(x);
- result.Add(value);
- });
- }
- return result;
- }
- }
- /// <summary>
- /// 判断某个数据是否已经被缓存
- /// </summary>
- public bool Exist<T>(string hashId, string key)
- {
- bool result = false;
- using (var redis = this.getRedisClient())
- {
- result = redis.HashContainsEntry(hashId, key);
- }
- return result;
- }
- /// <summary>
- /// 存储数据到hash表
- /// </summary>
- public bool Set<T>(string hashId, string key, T t)
- {
- bool result = false;
- try
- {
- using (var redis = this.getRedisClient())
- {
- var value = JsonConvert.SerializeObject(t);
- result = redis.SetEntryInHash(hashId, key, value);
- }
- }
- catch
- {
- result = false;
- }
- return result;
- }
- /// <summary>
- /// 移除hash中的某值
- /// </summary>
- public bool Remove(string hashId, string key)
- {
- bool result = false;
- try
- {
- using (var redis = this.getRedisClient())
- {
- result = redis.RemoveEntryFromHash(hashId, key);
- }
- }
- catch
- {
- result = false;
- }
- return result;
- }
- /// <summary>
- /// 移除整个hash
- /// </summary>
- public bool RemoveAll(string hashId)
- {
- bool result = false;
- using (var redis = this.getRedisClient())
- {
- result = redis.Remove(hashId);
- }
- return result;
- }
- /// <summary>
- /// 设置缓存过期
- /// </summary>
- public void SetExpire(string hashId, DateTime datetime)
- {
- using (var redis = this.getRedisClient())
- {
- redis.ExpireEntryAt(hashId, datetime);
- }
- }
- #endregion
- #region 保存到硬盘
- /// <summary>
- /// 保存数据DB文件到硬盘
- /// </summary>
- public void Save()
- {
- using (var redis = this.getRedisClient())
- {
- redis.Save();
- }
- }
- /// <summary>
- /// 异步保存数据DB文件到硬盘
- /// </summary>
- public void SaveAsync()
- {
- using (var redis = this.getRedisClient())
- {
- redis.SaveAsync();
- }
- }
- #endregion
- }
- }
操作:
- //var key = "AoVxQ-hvZGB6occUbGNiO-f4hiWzVhbYARheytOP5CyE";
- //for (var i = 0; i < 10; i++)
- //{
- // RedisCommon.getInstance.Set<String>("hongda", key + (i + 1), "hongda" + (i + 1));
- //}
- //RedisCommon.getInstance.Set<String>("hongda", "AoVxQ-hvZGB6occUbGNiO-f4hiWzVhbYARheytOP5CyE9", "hongda9999");
- //var aa=RedisCommon.getInstance.GetAll<string>("hongda");
- //var bb =RedisCommon.getInstance.Get<string>("hongda", "AoVxQ-hvZGB6occUbGNiO-f4hiWzVhbYARheytOP5CyE9");
- //RedisCommon.getInstance.Remove("hongda", "AoVxQ-hvZGB6occUbGNiO-f4hiWzVhbYARheytOP5CyE8");
- RedisCommon.getInstance.RemoveAll("hongda");
第三方的更完善版本:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Configuration;
- using ServiceStack.Redis;
- namespace Rongzi.BZone.Common.Util
- {
- public class RedisBase
- {
- private static string RedisPath = ConfigurationManager.AppSettings["RedisPath"];
- #region -- 连接信息 --
- //10.0.18.8:6379
- public static PooledRedisClientManager prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath });
- 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.GetClient())
- {
- return redis.GetListCount(key);
- }
- }
- public static List<T> List_GetRange<T>(string key, int start, int count)
- {
- using (IRedisClient redis = prcm.GetClient())
- {
- 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.GetClient())
- {
- 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.GetClient())
- {
- 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.GetClient())
- {
- 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.GetClient())
- {
- 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.GetClient())
- {
- 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.GetClient())
- {
- 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.GetClient())
- {
- 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);
- }
- }
- //public static double SortedSet_GetItemScore<T>(string key,T t)
- //{
- // using (IRedisClient redis = prcm.GetClient())
- // {
- // var data = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
- // return redis.GetItemScoreInSortedSet(key, data);
- // }
- // return 0;
- //}
- #endregion
- }
- }
http://blog.csdn.net/wanlong360599336/article/details/46771477
http://blog.wx6.org/2013/349.htm
Redis一些基本的操作的更多相关文章
- Jedis对Redis的常用命令操作
本篇主要总结一些Jedis对Redis的常用命令操作: 1.对key操作命令 2.对String操作命令 3.对List操作命令 4.对Set操作命令 5.对Hash操作命令 6.排序操作指令 一.项 ...
- Redis五大数据类型以及操作
目录: 一.redis的两种链接方式 二.redis的字符串操作(string) 三.redis的列表操作(list) 四.redis的散列表操作(类似于字典里面嵌套字典) 五.redis的集合操作( ...
- redis 五大数据类型以及操作
一.redis的两种链接方式 1.简单连接 import redis conn = redis.Redis(host='10.0.0.200',port=6379) conn.set('k1','年后 ...
- redis(Springboot中封装整合redis,java程序如何操作redis的5种基本数据类型)
平常测试redis操作命令,可能用的是cmd窗口 操作redis,记录一下 java程序操作reids, 操作redis的方法 可以用Jedis ,在springboot 提供了两种 方法操作 Red ...
- 【Redis】使用Jedis操作Redis
Jedis介绍 jedis就是集成了redis的一些命令操作,封装了redis的java客户端. Jedis使用 使用jedis需要引入jedis的jar包,下面提供了maven依赖 jedis.ja ...
- Redis学习---Redis的免密操作
Redis的免密操作 问题解决[方式一]:当前这种linux配置redis密码的方法是一种临时的,如果redis重启之后密码就会失效 1.首先进入redis,如果没有开启redis则需要先开启: [r ...
- 第三百节,python操作redis缓存-其他常用操作,用于操作redis里的数据name,不论什么数据类型
python操作redis缓存-其他常用操作,用于操作redis里的数据name,不论什么数据类型 delete(*names)根据删除redis中的任意数据类型 #!/usr/bin/env pyt ...
- springmvc+mybatis+redis实现查询插入操作
最近在学习redis,虽然现在还不是很熟练.不过可以进行简单的框架整合开发. IDE:我使用的是IDEA.springmvc+spring+mybatis的整合这个我就不多说了,下面我们先进行这块的整 ...
- Redis五大数据类型及操作
目录: 一.redis的两种链接方式 二.redis的字符串操作(string) 三.redis的列表操作(list) 四.redis的散列表操作(类似于字典里面嵌套字典) 五.redis的集合操作( ...
- [ecmagent][redis学习][1初识redis] redis安装+redis快速教程+python操作redis
# redis安装 # redis安装教程 -- 服务器(ubuntu)安装redis服务 sudo apt-get install redis-server -- 源码安装 -- $ wget ht ...
随机推荐
- [转]禁用和启用链接(a元素|LinkButton)的js方法
本文转自:http://www.cnblogs.com/beiguren/archive/2010/05/24/1742926.html 在Asp.net中,有时候需要禁用掉一个a链接元素. 在服务器 ...
- 安装Bind过程中提示丢失MSVCR110.dll的解决办法
前几天在线安装Visual Studio 2012 Update 3,由于在线安装需要不断下载安装文件,时间很长,后来等不下去,就取消了,不幸的是VS启动不了了,弹出“devenv.exe – 系统错 ...
- 8. Add the dashboard
Controller Node: 1. sudo apt-get install apache2 memcached libapache2-mod-wsgi openstack-dashboard ...
- 获取文本文件的第N行内容
在PowerShell中,可以通过Get-Content这个cmdlet来获取文本文件的内容.Get-Content将一个文本文件读取到一个数组中,每一个数组元素就是文件的一行内容.比如一个文本文件内 ...
- WITCH CHAPTER 0 [cry] 绝密开发中的史克威尔艾尼克斯的DX12技术演示全貌
西川善司的[WITCH CHAPTER 0 cry]讲座 ~绝密开发中的史克威尔艾尼克斯的DX12技术演示全貌 注:日文原文地址: http://pc.watch.impress.co.jp/d ...
- 自用有线IP切换
@echo ※※※※※※※※※※※※※※※※※※※※※※※※※※※※ @echo ※ ※ @echo ※ 本命令用于设置外网视频与内网打印切换IP地址 ※ @echo ※ ※ @echo ※ ※ @e ...
- mysqli_multi_query($link, $wsql)
if (mysqli_multi_query($link, $wsql)) { do { if ($result = mysqli_store_result($link)) { mysqli_free ...
- freebsd 禁用root登录ssh并给普通用户登录权限
转自http://www.linux521.com/2009/system/200904/2021.html http://www.myhack58.com/Article/48/67/2011/30 ...
- C#调用NPOI组件导出Excel表格
把一个List集合的数据导出到Excel表格中 public static string RenderToExcel<T>(List<T> datas) { MemoryStr ...
- 切记CMYK图片格式在IE中将无法显示
目前为止微软的Internet Explorer 浏览器IE6,IE7,IE8都不支持CMYK颜色模式图像 ,除IE外其他浏览器均能支持!所以大家要注意了 要选择RGB颜色模式,就可以了.