Redis 的发布订阅功能
redis 配置
Redis配置讲解(操作完记得重启Redis服务)
允许远程访问
1.修改两个配置文件:redis.windows.conf 和 redis.windows-service.conf 2.注释掉 bind 127.0.0.1 3.关闭保护模式 protected-mode no
密码
1.修改两个配置文件:redis.windows.conf 和 redis.windows-service.conf 2.开启 requirepass yourPassword
ASP.NET Core 使用redis
- 安装StackChange.Redis nuget包
- 连接字符串等数据库连接信息放在appsettings 中
- 编写数据库访问工具类
- startup注册服务
这里是手动解析配置信息,可以通过softjson自动解析
代码语言:javascript复制 public void ConfigureServices(IServiceCollection services)
{
var section = Configuration.GetSection("Redis:Default");
string _connectionString = section.GetSection("Connection").Value;
string _instanceName = section.GetSection("InstanceName").Value;
int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0");
services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));
services.AddControllers();
}
- controller 中调用
ASP.NET CORE 中使用redis缓存
安装nuget 包
- StackExchange.Redis.Extensions.Core
- StackExchange.Redis.Extensions.AspNetCore
- StackExchange.Redis.Extensions.Newtonsoft
appsettings配置文件添加
代码语言:javascript复制"Redis": {
"Password": "123456",
"AllowAdmin": true,
"Ssl": false,
"ConnectTimeout": 6000,
"ConnectRetry": 2,
"Database": 0,
"Hosts": [
{
"Host": "127.0.0.1",
"Port": "6379"
}
]
}
startup 注册服务
代码语言:javascript复制public void ConfigureServices(IServiceCollection services)
{
var redisConfiguration = Configuration.GetSection("Redis").Get<RedisConfiguration>();
services.AddControllersWithViews();
services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration);
}
服务注入
代码语言:javascript复制 private readonly RedisCacheClient _redisCacheClient;
public TestController(IRedis redisCacheClient)
{
_redisCacheClient = redisCacheClient;
}
使用
代码语言:javascript复制 public async Task<IActionResult> Index4()
{
var productdata = await _redisCacheClient.Db0.GetAsync<Product>("Product");
return View();
}
.net 中 redis 的发布订阅
主要使用代码:订阅
代码语言:javascript复制using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
{
ISubscriber sub = redis.GetSubscriber();
//订阅名为 messages 的通道
sub.Subscribe("messages", (channel, message) => {
//输出收到的消息
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
});
Console.WriteLine("已订阅 messages");
Console.ReadKey();
}
发布
代码语言:javascript复制//创建连接
using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
{
ISubscriber sub = redis.GetSubscriber();
Console.WriteLine("请输入任意字符,输入exit退出");
string input;
do
{
input = Console.ReadLine();
sub.Publish("messages", input);
} while (input != "exit");
}