项目实战 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 终于写出一个 ...
随机推荐
- duilib
https://www.cnblogs.com/lin1270/p/4109305.html
- .net 获取远程访问的ip
这两天一直做获取远程访问的ip和自己的ip相关的问题. 在解决获取ip相关问题的时候,主要使用了上下文对象,httpcontext对象.原理很简单,内部有两大对象,request和response.里 ...
- Kerberos原理
前些日子为了搞清楚Kerberos原理,把MIT的Kerberos经典对话看了几遍,终于有了一个稍微清晰的认识,这里稍微记录下,因为Kerberos是使用传统加密技术实现的一个认证机制,所以顺便备忘下 ...
- c# 判断一个string[]是否全包含另一个string[]
// list = normalList.Except(repairList).ToList(); //差集 // list = normalList.Union(repairList).ToList ...
- adb.exe 已停止工作 解决
netstat -aon|findstr 5037tasklist /fi "PID eq 10388"TASKKILL /F /IM PPAdbServer.exe
- js字符串轉數組,數組轉字符串
字符串轉數組:split(',') 數組轉字符串:join(‘,’) https://www.cnblogs.com/woodk/p/5714329.html
- Civil 3D .NET二次开发第11章代码升级至2018版注意事项
原来涉及2017的,均需要改为2018 原来的21改为22 代码中AeccXUiLand.AeccApplication.11.0"改为AeccXUiLand.AeccApplication ...
- python之旅九【第九篇】socket
什么是socket 建立网络通信连接至少要一对端口号(socket).socket本质是编程接口(API),对TCP/IP的封装,TCP/IP也要提供可供程序员做网络开发所用的接口,这就是Socket ...
- ajax 跨域 springboot
CORS 定义 Cross-Origin Resource Sharing(CORS)跨来源资源共享是一份浏览器技术的规范,提供了 Web 服务从不同域传来沙盒脚本的方法,以避开浏览器的同源策略,是 ...
- 【洛谷P3899】谈笑风生
题目大意:给定一棵 N 个节点的有根树,1 号节点为根节点,现给出 Q 个询问,每次询问距离 u 号节点不超过 K 的节点 b,c 为 a 与 b 的后代,求这样的三元组有多少个. 题解:学会了线段树 ...