项目实战 redis 缓存
1 首先在你的项目中,引用以下ServiceStack.Redis相关的四个类库。或者通过Nuget进行安装Redis常用组件ServiceStack.Redis。 下载示例代码。

2. 创建一个Redis操作的公用类RedisCacheHel
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace WEBJSM.Models
{
class RedisCacheHelper
{
private static readonly PooledRedisClientManager pool = null;
private static readonly string[] redisHosts = null;
public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
static RedisCacheHelper()
{
var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];
if (!string.IsNullOrEmpty(redisHostStr))
{
redisHosts = redisHostStr.Split(',');
if (redisHosts.Length > 0)
{
pool = new PooledRedisClientManager(redisHosts, redisHosts,
new RedisClientManagerConfig()
{
MaxWritePoolSize = RedisMaxWritePool,
MaxReadPoolSize = RedisMaxReadPool,
AutoStart = true
});
}
}
}
public static void Add<T>(string key, T value, DateTime expiry)
{
if (value == null)
{
return;
}
if (expiry <= DateTime.Now)
{
Remove(key);
return;
}
try
{
if (pool != null)
{
using (var r = pool.GetClient())
{
if (r != null)
{
r.SendTimeout = 1000;
r.Set(key, value, expiry - DateTime.Now);
}
}
}
}
catch (Exception ex)
{
string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
}
}
public static void Add<T>(string key, T value, TimeSpan slidingExpiration)
{
if (value == null)
{
return;
}
if (slidingExpiration.TotalSeconds <= 0)
{
Remove(key);
return;
}
try
{
if (pool != null)
{
using (var r = pool.GetClient())
{
if (r != null)
{
r.SendTimeout = 1000;
r.Set(key, value, slidingExpiration);
}
}
}
}
catch (Exception ex)
{
string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
}
}
public static T Get<T>(string key)
{
if (string.IsNullOrEmpty(key))
{
return default(T);
}
T obj = default(T);
try
{
if (pool != null)
{
using (var r = pool.GetClient())
{
if (r != null)
{
r.SendTimeout = 1000;
obj = r.Get<T>(key);
}
}
}
}
catch (Exception ex)
{
string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
}
return obj;
}
public static void Remove(string key)
{
try
{
if (pool != null)
{
using (var r = pool.GetClient())
{
if (r != null)
{
r.SendTimeout = 1000;
r.Remove(key);
}
}
}
}
catch (Exception ex)
{
string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
}
}
public static bool Exists(string key)
{
try
{
if (pool != null)
{
using (var r = pool.GetClient())
{
if (r != null)
{
r.SendTimeout = 1000;
return r.ContainsKey(key);
}
}
}
}
catch (Exception ex)
{
string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
}
return false;
}
}
}
说明:RedisCacheHelper 使用的是客户端链接池模式,这样的存取效率应该是最高的。同时也更方便的支持读写分离,均衡负载。
3. 配置文件写在web.config 的 appSettings 节点下
<add key="SessionExpireMinutes" value="180" />
<add key="redis_server_session" value="127.0.0.1:6379" />
<add key="redis_max_read_pool" value="3" />
<add key="redis_max_write_pool" value="1" />
4. 测试程序调用
RedisCacheHelper.Add("name1", UserDspName, DateTime.Now.AddDays(1)); //存数据
string str = RedisCacheHelper.Get<string>("name1"); //取数据
项目实战 redis 缓存的更多相关文章
- SpringBoot微服务电商项目开发实战 --- Redis缓存雪崩、缓存穿透、缓存击穿防范
最近已经推出了好几篇SpringBoot+Dubbo+Redis+Kafka实现电商的文章,今天再次回到分布式微服务项目中来,在开始写今天的系列五文章之前,我先回顾下前面的内容. 系列(一):主要说了 ...
- SpringBoot电商项目实战 — Redis实现分布式锁
最近有小伙伴发消息说,在Springboot系列文第二篇,zookeeper是不是漏掉了?关于这个问题,其实我在写第二篇的时候已经考虑过,但基于本次系列文章是实战练习,在项目里你能看到Zookeepe ...
- 基于 abp vNext 和 .NET Core 开发博客项目 - 使用Redis缓存数据
上一篇文章(https://www.cnblogs.com/meowv/p/12943699.html)完成了项目的全局异常处理和日志记录. 在日志记录中使用的静态方法有人指出写法不是很优雅,遂优化一 ...
- springboot项目:Redis缓存使用
保存Redis 第一步:启动类中加入注解 @EnableCaching package com.payease; import org.springframework.boot.SpringAppli ...
- 商铺项目(Redis缓存)
AOF,RDB是两种 redis持久化的机制.用于crash后,redis的恢复. 两种区别就是,AOF是持续的用日志记录写操作,crash后利用日志恢复:RDB是平时写操作的时候不触发写,只有手动提 ...
- Java 18套JAVA企业级大型项目实战分布式架构高并发高可用微服务电商项目实战架构
Java 开发环境:idea https://www.jianshu.com/p/7a824fea1ce7 从无到有构建大型电商微服务架构三个阶段SpringBoot+SpringCloud+Solr ...
- 基于Python项目的Redis缓存消耗内存数据简单分析(附详细操作步骤)
目录 1 准备工作 2 具体实施 1 准备工作 什么是Redis? Redis:一个高性能的key-value数据库.支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使 ...
- spring boot redis 缓存(cache)集成
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- 【无私分享:ASP.NET CORE 项目实战(第十一章)】Asp.net Core 缓存 MemoryCache 和 Redis
目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitHub上下载了十几个源码参考, Memory 和 Redis 终于写出一个 ...
随机推荐
- python之面相对象程序设计
一 面向对象的程序设计的由来 面向对象设计的由来见概述:http://www.cnblogs.com/linhaifeng/articles/6428835.html 面向对象的程序设计:路飞学院版 ...
- web框架开发-Django模型层(2)-多表操作
很重要,都是精华 多表关系模型 一对一 一旦确定表关系是一对一,在两张表中的任意一张表中建立关联字段+Unique 一对多 一旦确定表关系是一对多,创建关联字段在多的表中 多对多 一旦确定表关系是多对 ...
- Openssl x509命令
一.简介 x509指令是一个功能很丰富的证书处理工具.可以用来显示证书的内容,转换其格式,给CSR签名等 二.语法 openssl x509 [-inform DER|PEM|NET] [-outfo ...
- python 中内存释放与函数传递numpy数组问题
numpy.array 作为参数传入函数中时,是作为引用进去的,函数内部对这个数组的修改会直接修改原始数据.在函数中需要暂时修改数据,不对原始数据造成影响的话,需要用 np.copy() 先拷贝一份, ...
- python 角度和弧度转化
>>> import math >>> math.degrees(math.pi/) 90.0 >>> math.radians() 1.5707 ...
- CGPoint、CGSize、CGRect、CGRectEdge的详细使用
http://blog.sina.com.cn/s/blog_953e22700101r7lz.html 在CGGeometry.h里的 CGPoint.CGSize.CGRect.CGRectEdg ...
- git命令行 整理(一位大神给我的私藏)
Evernote Export Git 是一个很强大的分布式版本控制系统.它不但适用于管理大型开源软件的源代码,管理私人的文档和源代码也有很多优势. Git常用操作命令: 1) 远程仓库相关命令 检出 ...
- Mac之lnmp环境搭建
之前在Windows上开发大部分都是使用的集成环境(xampp,phpstudy,wamp),可以完成日常便捷开发,有些时候却Windows下无法实现的就需要自己搭建虚拟机,在虚拟机中搭建lnmp环境 ...
- js计算两个日期的月份差?
//两个日期 var date1 = '2013-03-26'; var date2 = '2011-01-10'; // 拆分年月日 date1 = date1.split('-'); // 得到月 ...
- 一招明白URL和URI的区别
URL和URI的区别(示例): URL[统一资源定位器]: http://localhost:8080/api/account/queryAccountInfo URI[统一资源定位符]: /api/ ...