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 缓存的更多相关文章

  1. SpringBoot微服务电商项目开发实战 --- Redis缓存雪崩、缓存穿透、缓存击穿防范

    最近已经推出了好几篇SpringBoot+Dubbo+Redis+Kafka实现电商的文章,今天再次回到分布式微服务项目中来,在开始写今天的系列五文章之前,我先回顾下前面的内容. 系列(一):主要说了 ...

  2. SpringBoot电商项目实战 — Redis实现分布式锁

    最近有小伙伴发消息说,在Springboot系列文第二篇,zookeeper是不是漏掉了?关于这个问题,其实我在写第二篇的时候已经考虑过,但基于本次系列文章是实战练习,在项目里你能看到Zookeepe ...

  3. 基于 abp vNext 和 .NET Core 开发博客项目 - 使用Redis缓存数据

    上一篇文章(https://www.cnblogs.com/meowv/p/12943699.html)完成了项目的全局异常处理和日志记录. 在日志记录中使用的静态方法有人指出写法不是很优雅,遂优化一 ...

  4. springboot项目:Redis缓存使用

    保存Redis 第一步:启动类中加入注解 @EnableCaching package com.payease; import org.springframework.boot.SpringAppli ...

  5. 商铺项目(Redis缓存)

    AOF,RDB是两种 redis持久化的机制.用于crash后,redis的恢复. 两种区别就是,AOF是持续的用日志记录写操作,crash后利用日志恢复:RDB是平时写操作的时候不触发写,只有手动提 ...

  6. Java 18套JAVA企业级大型项目实战分布式架构高并发高可用微服务电商项目实战架构

    Java 开发环境:idea https://www.jianshu.com/p/7a824fea1ce7 从无到有构建大型电商微服务架构三个阶段SpringBoot+SpringCloud+Solr ...

  7. 基于Python项目的Redis缓存消耗内存数据简单分析(附详细操作步骤)

    目录 1 准备工作 2 具体实施   1 准备工作 什么是Redis? Redis:一个高性能的key-value数据库.支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使 ...

  8. spring boot redis 缓存(cache)集成

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  9. 【无私分享:ASP.NET CORE 项目实战(第十一章)】Asp.net Core 缓存 MemoryCache 和 Redis

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitHub上下载了十几个源码参考, Memory 和 Redis 终于写出一个 ...

随机推荐

  1. elementUI el-select 中disabled设置

    <el-select v-model="userForm.roleName" placeholder="请选择用户角色" :disabled=" ...

  2. Linux-基础学习(五)-mariadb主从复制以及redis学习

    开始今日份整理 1.mariadb的主从复制 主从复制大致图示: 1.1 mysql基本命令复习 linux下的操作 .启动mysql systemctl start mariadb .linux客户 ...

  3. HBase原理分析

    宏观架构 HBase从宏观上看只有HMaster.RegionServer和zookeeper三个组件. Master: 负责启动的时候分配Region到具体的RegionServer,执行各种管理操 ...

  4. 使用sz/rz基于串口传输文件

    关键词:lrzsz.minicom.ZMODEM.MD5sum等. 在环境受限的嵌入式系统上,往往只有串口可以使用. 此时如果需要传输文件,需要借助rz/sz工具,可以使用的传输协议有ZMODEM.Y ...

  5. JDK1.8源码(十)——java.util.LinkedHashSet类

    同 HashSet 与 HashMap 的关系一样,本篇博客所介绍的 LinkedHashSet 和 LinkedHashMap 也是一致的.在 JDK 集合框架中,类似 Set 集合通常都是由对应的 ...

  6. python新式类与旧式类

    python2.X是经典类[旧式类]: 是以深度优先[] 但是在Python2.x中,默认都是经典类,只有显式继承了object才是新式类,即:class Person(object):pass 新式 ...

  7. ARC089E GraphXY 构造

    传送门 在Luogu上评了"NOI"之后评级变成了"普及+/提高"--我觉得我可能要退群了 考虑构造一个这样的图: 其中上半部分是从\(S\)开始的一条长\(1 ...

  8. Linux利用mysql建立数据库

    安装数据库: sudo   apt-get  install  mysql-server   启动服务: sudo  service  mysql  start  连接数据库:sudo    mysq ...

  9. (hdu 6024) Building Shops

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6024 Problem Description HDU’s n classrooms are on a ...

  10. 第二部分之RDB持久化(第十章)

    RDB持久化功能所生成的RDB文件是一个经过压缩的二进制文件,通过该文件可以还原生成RDB文件时的数据库状态.(数据库状态:服务器中的非空数据库以及它们的键值对统称为数据库状态) 一.RDB文件的创建 ...