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
这里是手动解析配置信息,可以通过softjson自动解析
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();
}
安装nuget 包
appsettings配置文件添加
"Redis": {
"Password": "123456",
"AllowAdmin": true,
"Ssl": false,
"ConnectTimeout": 6000,
"ConnectRetry": 2,
"Database": 0,
"Hosts": [
{
"Host": "127.0.0.1",
"Port": "6379"
}
]
}
startup 注册服务
public void ConfigureServices(IServiceCollection services)
{
var redisConfiguration = Configuration.GetSection("Redis").Get<RedisConfiguration>();
services.AddControllersWithViews();
services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration);
}
服务注入
private readonly RedisCacheClient _redisCacheClient;
public TestController(IRedis redisCacheClient)
{
_redisCacheClient = redisCacheClient;
}
使用
public async Task<IActionResult> Index4()
{
var productdata = await _redisCacheClient.Db0.GetAsync<Product>("Product");
return View();
}
主要使用代码:订阅
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();
}
发布
//创建连接
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");
}