2.Asp.net Core使用Redis-StackExchange.Redis操作

本文介绍了如何在Asp.net Core中使用StackExchange.Redis库操作Redis,包括启动Redis服务、配置参数、连接Redis数据库,以及详细探讨了Redis中的五大数据类型:String、Hash、List、Set和ZSet的特性和应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档地址:https://stackexchange.github.io/StackExchange.Redis/
核心对象是ConnectionMultiplexer 类,在调用者之间共享和重用。线程安全

一、运行Redis Server

首先确保redis服务端已开启,下载redis server请参考https://stackexchange.github.io/StackExchange.Redis/Server

二、配置参数

当调用Connect (or ConnectAsync)传入配置模型

var conn = ConnectionMultiplexer.Connect(configuration);

提供了两种配置方式:

  • ConfigurationOptions 实例
  • 配置字符串

1.字符串参数配置方式

最简单的配置如下:

//This will connect to a single server on the local machine using the default redis port (6379)
var conn = ConnectionMultiplexer.Connect("localhost");
//添加其他选项以逗号分隔 参数配置name=value
var conn = ConnectionMultiplexer.Connect("redis0:6380,redis1:6380,allowAdmin=true,password=123456");

//如果指定serviceName将触发哨兵模式,本示例将使用默认的哨兵端口(26379)连接到本地机器上的哨兵服务器。发现myprimary服务的当前主服务器,并返回指向主服务器的托管连接,如果主服务器发生变化,该连接将自动更新:
var conn = ConnectionMultiplexer.Connect("localhost,serviceName=myprimary");

// string and ConfigurationOptions 切换
ConfigurationOptions options = ConfigurationOptions.Parse(configString);
string configString = options.ToString();

一个常见的用法是将基本的详细信息存储在字符串中,然后在运行时应用特定的详细信息:

string configString = GetRedisConfiguration();
var options = ConfigurationOptions.Parse(configString);
options.ClientName = GetAppName(); // only known at runtime
options.AllowAdmin = true;
conn = ConnectionMultiplexer.Connect(options);
//Microsoft Azure Redis example with password
var conn = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,ssl=true,password=...");

三、使用redis database

IDatabase db = redis.GetDatabase();

//多数据可以指定需要读取的数据库
var db2 = redis.GetDatabase(7);

//如果在api中需要使用异步,可以使用Task.AsyncState 来指定一个值



四、Redis中的数据类型及操作

1.string 存储简单的键值对,最大能存储 512MB

string 类型是二进制安全的。意思是 redis 的 string 可以包含任何数据。比如jpg图片或者序列化的对象,json字符串。

 		[HttpGet(Name = "StringTest")]
        public string StringTest(string key)
        {
   
            string mess = "";
            var redis = ConnectionMultiplexer.Connect("192.168.100.86:6379,allowAdmin=true,password=123456");
            var db = redis.GetDatabase();
            bool haskey = db.KeyExists
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值