C# Redis Server分布式缓存编程(一)
这篇文章我将介绍如果用最简洁的方式配置Redis Server,
以及如何使用C#和它交互编程
一. 背景介绍
Redis是最快的key-value分布式缓存之一
缺点: 没有本地数据缓冲, 目前还没有完整的数据聚集化支持
优点: 配置简单, 使用方便, 高性能,支持不同的数据类型(hashes, lists, sets, sorted sets)
ASP.NET WebUI for viewing content of the cache
二. 安装Redis
1) 从github下载最新的32/64位安装
https://github.com/dmajkic/redis/downloads
解压到你自己的目录
eg: d:\RedisServer
2) 从github下载Redis服务程序
dll手工版
https://github.com/kcherenkov/redis-windows-service/downloads
安装版
https://github.com/rgl/redis/downloads
拷贝到RedisServer的安装目录
eg: d:\RedisServer
3) 安装redis服务
进入你的应用程序目录,运行下面的命令
sc create %name% binpath= "\"%binpath%\" %configpath%" start= "auto" DisplayName= "Redis"
%name% -- name of service instance, ex. redis-instance;
%binpath% -- path to this project exe file, ex. C:\Program Files\Redis\RedisService_1.1.exe;
%configpath% -- path to redis configuration file, ex. C:\Program Files\Redis\redis.conf;
sc create my-redis binpath= "\"D:\RedisServer\RedisService_1.1.exe\" D:\RedisServer\redis.conf" start= "auto" DisplayName= "MyRedis"
4) 基本配置
redis.conf
# requirepass foobared
去掉注释,重启服务
这样实例化一个Redis服务的时候,就需要密码
RedisClient client = new RedisClient(serverHost, port, redisPassword);
Redis server replication (master - slave配置)
# slaveof <masterip> <masterport>
eg:
slaveof 192.168.1.1 6379
三. 客户端编程
1) 安装Redis包
2) 简单例子
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ServiceStack.Redis; using System.Threading; namespace Zeus.Cache.Redis.Demo { public class SimpleRedisDemo { public void SimpleDemo() { string host = "localhost"; string elementKey = "testKeyRedis"; using (RedisClient redisClient = new RedisClient(host)) { if (redisClient.Get<string>(elementKey) == null) { // adding delay to see the difference Thread.Sleep(2000); // save value in cache redisClient.Set(elementKey, "default value"); } //change the value redisClient.Set(elementKey, "fuck you value"); // get value from the cache by key string message = "Item value is: " + redisClient.Get<string>(elementKey); Console.WriteLine(message); } } } }
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
2009-08-16 JQuery UI库 - Dialog