原文:使用ServiceStack.Redis实现Redis数据读写

User.cs实体类

public class User
{
public string Name { get; set; }
public int Id { get; set; }
}

Program.cs

 class Program
{
private static readonly RedisHelper redisHelper = new RedisHelper(true); private static void Main(string[] args)
{
var u = new User { Name = "eric1", Id = 1 };
redisHelper.Set("user", u); //设置缓存
u = redisHelper.Get<User>("user");
Console.WriteLine(u.Name); var list = new List<User>
{
new User {Name = "永远强大的领导者1", Id = 1},
new User {Name = "永远强大的领导者2", Id = 2}
}; redisHelper.Remove("list1"); //删除缓存
redisHelper.AddList("list1", list); //添加缓存链表
redisHelper.AddEntityToList("list1", new User { Name = "永远强大的领导者3", Id = 3 });
list = redisHelper.GetList<User>("list1").ToList();
Console.WriteLine(list.Count); //队列
redisHelper.RemoveEntityFromList("list1", list[0]);
redisHelper.RemoveEntityFromList<User>("list1", it => it.Id == 2);
list = redisHelper.GetList<User>("list1").ToList();
Console.WriteLine(list.Count); redisHelper.Flushall();
redisHelper.Dispose();
Console.ReadLine();
}
}

RedisHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic; namespace myRtest
{
public class RedisHelper : IDisposable
{
public RedisClient Redis = new RedisClient("127.0.0.1", 6379, "123456");
//缓存池
private PooledRedisClientManager prcm = new PooledRedisClientManager(); //默认缓存过期时间单位秒
public int secondsTimeOut = 30 * 60; /// <summary>
/// 构造函数
/// </summary>
/// <param name="OpenPooledRedis">是否开启缓冲池</param>
public RedisHelper(bool OpenPooledRedis = false)
{
if (OpenPooledRedis)
{
prcm = CreateManager(new[] { "123456@127.0.0.1:6379" }, new[] { "123456@127.0.0.1:6379" });
Redis = prcm.GetClient() as RedisClient;
}
} #region Key/Value存储 /// <summary>
/// 设置缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">缓存建</param>
/// <param name="t">缓存值</param>
/// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间</param>
/// <returns></returns>
public bool Set<T>(string key, T t, int timeout = 0)
{
if (timeout >= 0)
{
if (timeout > 0)
{
secondsTimeOut = timeout;
}
Redis.Expire(key, secondsTimeOut);
} return Redis.Add(key, t);
} /// <summary>
/// 获取
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T Get<T>(string key)
{
return Redis.Get<T>(key);
} /// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Remove(string key)
{
return Redis.Remove(key);
} public bool Add<T>(string key, T t, int timeout)
{
if (timeout >= 0)
{
if (timeout > 0)
{
secondsTimeOut = timeout;
}
Redis.Expire(key, secondsTimeOut);
}
return Redis.Add(key, t);
} #endregion #region 链表操作 /// <summary>
/// 根据IEnumerable数据添加链表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listId"></param>
/// <param name="values"></param>
/// <param name="timeout"></param>
public void AddList<T>(string listId, IEnumerable<T> values, int timeout = 0)
{
Redis.Expire(listId, 60);
IRedisTypedClient<T> iredisClient = Redis.As<T>();
if (timeout >= 0)
{
if (timeout > 0)
{
secondsTimeOut = timeout;
}
Redis.Expire(listId, secondsTimeOut);
}
IRedisList<T> redisList = iredisClient.Lists[listId];
redisList.AddRange(values);
iredisClient.Save();
} /// <summary>
/// 添加单个实体到链表中
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listId"></param>
/// <param name="Item"></param>
/// <param name="timeout"></param>
public void AddEntityToList<T>(string listId, T Item, int timeout = 0)
{
IRedisTypedClient<T> iredisClient = Redis.As<T>();
if (timeout >= 0)
{
if (timeout > 0)
{
secondsTimeOut = timeout;
}
Redis.Expire(listId, secondsTimeOut);
}
IRedisList<T> redisList = iredisClient.Lists[listId];
redisList.Add(Item);
iredisClient.Save();
} /// <summary>
/// 获取链表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listId"></param>
/// <returns></returns>
public IEnumerable<T> GetList<T>(string listId)
{
IRedisTypedClient<T> iredisClient = Redis.As<T>();
return iredisClient.Lists[listId];
} /// <summary>
/// 在链表中删除单个实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listId"></param>
/// <param name="t"></param>
public void RemoveEntityFromList<T>(string listId, T t)
{
IRedisTypedClient<T> iredisClient = Redis.As<T>();
IRedisList<T> redisList = iredisClient.Lists[listId];
redisList.RemoveValue(t);
iredisClient.Save();
} /// <summary>
/// 根据lambada表达式删除符合条件的实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listId"></param>
/// <param name="func"></param>
public void RemoveEntityFromList<T>(string listId, Func<T, bool> func)
{
using (IRedisTypedClient<T> iredisClient = Redis.As<T>())
{
IRedisList<T> redisList = iredisClient.Lists[listId];
T value = redisList.Where(func).FirstOrDefault();
redisList.RemoveValue(value);
iredisClient.Save();
}
} #endregion #region 清空Redis所有数据库中的所有key
public void Flushall()
{
Redis.FlushAll();
}
#endregion //释放资源
public void Dispose()
{
if (Redis != null)
{
Redis.Dispose();
Redis = null;
}
GC.Collect();
} /// <summary>
/// 缓冲池
/// </summary>
/// <param name="readWriteHosts"></param>
/// <param name="readOnlyHosts"></param>
/// <returns></returns>
public static PooledRedisClientManager CreateManager(
string[] readWriteHosts, string[] readOnlyHosts)
{
return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,
new RedisClientManagerConfig
{
MaxWritePoolSize = readWriteHosts.Length * 5,
MaxReadPoolSize = readOnlyHosts.Length * 5,
AutoStart = true,
});
// { RedisClientFactory = (IRedisClientFactory)RedisCacheClientFactory.Instance.CreateRedisClient("127.0.0.1", 6379) };
}
}
}

运行结果如图:

使用ServiceStack.Redis实现Redis数据读写的更多相关文章

  1. Redis缓存服务搭建及实现数据读写

    发现博客园中好多大牛在介绍自己的开源项目是很少用到缓存,比如Memcached.Redis.mongodb等,今天得空抽时间把Redis缓存研究了一下,写下来总结一下,跟大家一起分享 一下.由于小弟水 ...

  2. Redis缓存服务搭建及实现数据读写--转载

    来自 http://www.cnblogs.com/lc-chenlong/p/3218157.html 1.  下载安装Redis 下载地址:https://github.com/MSOpenTec ...

  3. Redis缓存服务搭建及实现数据读写 - Eric.Chen

    发现博客园中好多大牛在介绍自己的开源项目是很少用到缓存,比如Memcached.Redis.mongodb等,今天得空抽时间把Redis缓存研究了一下,写下来总结一下,跟大家一起分享 一下.由于小弟水 ...

  4. Redis系列之(二):Redis主从同步,读写分离

    1. Redis主从同步 Redis支持主从同步.数据可以从主服务器向任意数量的从服务器上同步,同步使用的是发布/订阅机制. 2. 配置主从同步 Mater Slave的模式,从Slave向Maste ...

  5. Memcache,Redis,MongoDB(数据缓存系统)方案对比与分析

    mongodb和memcached不是一个范畴内的东西.mongodb是文档型的非关系型数据库,其优势在于查询功能比较强大,能存储海量数据.mongodb和memcached不存在谁替换谁的问题. 和 ...

  6. Redis学习笔记~Redis主从服务器,读写分离

    回到目录 Redis这个Nosql的存储系统一般会被部署到linux系统中,我们可以把它当成是一个数据服务器,对于并发理大时,我们会使用多台服务器充当Redis服务器,这时,各个Redis之间也是分布 ...

  7. Redis系列之(二):Redis主从同步,读写分离(转)

    1. Redis主从同步 Redis支持主从同步.数据可以从主服务器向任意数量的从服务器上同步,同步使用的是发布/订阅机制. 2. 配置主从同步 Mater Slave的模式,从Slave向Maste ...

  8. linux安装redis及主从复制、读写分离、哨兵模式

    Redis安装与部署 版本最好选择3.0及以上.以后还可以部署Redis集群. 1.下载: [root@bogon redis-3.0.0]# cd /usr/local [root@bogon lo ...

  9. python+php+redis+shell实现几台redis的同步数据

    之所以使用python,是因为python多线程非常简单. 之所以使用shell,是因为写了个服务,可以方便的重启python写的那个脚本. 总体思路:利用redis的发布订阅,php作为生产者,py ...

随机推荐

  1. 【47.95%】【codeforces 554C】Kyoya and Colored Balls

    time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...

  2. 【codeforces 755B】PolandBall and Game

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  3. [React] Use React.cloneElement to Extend Functionality of Children Components

    We can utilize React.cloneElement in order to create new components with extended data or functional ...

  4. HTML中DOM对象的属性和方法的层级关系是怎样的?(目录即层次)

    HTML中DOM对象的属性和方法的层级关系是怎样的?(目录即层次) 一.总结 一句话总结:目录就是测试题 1.document取得元素(get element)的方式有哪几种? 解答:四种,分别是id ...

  5. 单个和多个checkbox选中事件怎么写

    单个和多个checkbox选中事件怎么写 一.总结 一句话总结: 1.checkbox的事件方法的话主要是change和click 2.checkbox的属性判断的话主要是prop(判断checked ...

  6. [TypeScript] Increase TypeScript's type safety with noImplicitAny

    TypeScript tries to infer as much about your code as it can. But sometimes there really is not enoug ...

  7. Node.js开发入门—使用AngularJS

    做一个Web应用,一般都有前台和后台,Node.js能够实现后台.利用jade模板引擎也能够生成一些简单的前台页面,但要想开发出具有实际意义的现代Web应用.还得搭配一个Web前端框架. Angula ...

  8. zookeeper 半数可用/选举机制

    1.半数可用机制,半数可用指的是zk集群中一半以上的机器正常时集群才能正常工作 已经启动了hadoop002(follower),hadoop003(leader) 下面停止hadoop002 在ha ...

  9. MapReduce 切片机制源码分析

    总体来说大概有以下2个大的步骤 1.连接集群(yarnrunner或者是localjobrunner) 2.submitter.submitJobInternal()在该方法中会创建提交路径,计算切片 ...

  10. JAVA SE回顾及思考(2)——数组的复制与动态扩展

    我们知道在Java中数组是非基本类型既数组是对象(Object)的子类,所以用下面的这种方式是不能复制该对象的 public static void main(String[] args) { int ...