redis 哨兵模式(二) .net core 连接 哨兵 三种中间件 ServiceStack.Redis StackExchange.Redis CSRedis

上一节 介绍了 构建哨兵 构建哨兵的 时候 每一个 哨兵是没有密码的  ,哨兵 是可以 有密码的  

每个哨兵 设置密码是在 配置文件 设置

requirepass 123456

 

其中 我没有 找到 CSRedis 中间件 连接 有密码的哨兵 其他 两个可以连接有密码的哨兵 

nuget下载  ServiceStack.Redis StackExchange.Redis  CSRedis

swagger 展示接口

 

using CSRedis;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceStack.DataAnnotations;
using ServiceStack.Redis;
using StackExchange.Redis;
using static StackExchange.Redis.Role;

namespace Redis操作WebApi.Controllers
{
    /// <summary>
    /// 哨兵
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SentinelController : ControllerBase
    {
        private readonly string HashKey = "User";
        private readonly string Prefix = "Student_";
        /// <summary>
        /// 哨兵
        /// </summary>
        public SentinelController()
        {

        }
        /// <summary>
        /// ServiceStack 哨兵无密码
        /// </summary>
        /// <returns></returns>
        [HttpGet("ServiceStackNoPassWord/{userId}")]
        public ActionResult ServiceStackNoPassWord([FromRoute] string userId)
        {
            //哨兵配置 无密码
            string[] hosts = new string[] { "192.168.0.168:26379", "192.168.0.168:26380", "192.168.0.168:26381" };
            var sentinel = new RedisSentinel(hosts, "local-master")
            {
                IpAddressMap = { { "192.168.0.168", "123456@192.168.0.168" } }
            };
            var redisManager = sentinel.Start();
            //var master = sentinel.GetMaster();
            //var slavers = sentinel.GetSlaves();
            //var c = redisManager.GetClient();
            using (var client = redisManager.GetClient())
            {

                if (client.HashContainsEntry(HashKey, Prefix + userId))
                {
                    string result = client.GetValueFromHash(HashKey, Prefix + userId);
                    Student student1 = JsonConvert.DeserializeObject<Student>(result);
                    return Ok(student1);
                }
                //如果没有 添加学生 做为测试 
                int studentId = Random.Shared.Next(1000, 99999);
                Student student = new Student { Id = studentId, Name = "小李" };
                client.SetEntryInHashIfNotExists(HashKey, Prefix + userId, JsonConvert.SerializeObject(student));
                return Ok(student);
            }
        }
        /// <summary>
        /// ServiceStack 哨兵有密码
        /// </summary>
        /// <returns></returns>
        [HttpGet("ServiceStackForPassWord/{userId}")]
        public ActionResult ServiceStackForPassWord([FromRoute] string userId)
        {
            // 哨兵配置 有密码
            string[] hosts = new string[] { "123456@192.168.0.168:26379", "123456@192.168.0.168:26380", "123456@192.168.0.168:26381" };
            var sentinel = new RedisSentinel(hosts, "local-master")
            {
                IpAddressMap = { { "192.168.0.168", "123456@192.168.0.168" } }
            };
            var redisManager = sentinel.Start();
            //var master = sentinel.GetMaster();
            //var slavers = sentinel.GetSlaves();
            //var c = redisManager.GetClient();
            using (var client = redisManager.GetClient())
            {

                if (client.HashContainsEntry(HashKey, Prefix + userId))
                {
                    string result = client.GetValueFromHash(HashKey, Prefix + userId);
                    Student student1 = JsonConvert.DeserializeObject<Student>(result);
                    return Ok(student1);
                }
                //如果没有 添加学生 做为测试 
                int studentId = Random.Shared.Next(1000, 99999);
                Student student = new Student { Id = studentId, Name = "小李" };
                client.SetEntryInHashIfNotExists(HashKey, Prefix + userId, JsonConvert.SerializeObject(student));
                return Ok(student);
            }
        }

        /// <summary>
        /// StackExchange 哨兵无密码
        /// </summary>
        /// <returns></returns>
        [HttpGet("StackExchangeNoPassWord/{userId}")]
        public ActionResult StackExchangeNoPassWord([FromRoute] string userId)
        {

            //redis 集群配置有密码
            string con = "192.168.0.168:6379,192.168.0.168:6380,192.168.0.168:6381";
            ConnectionMultiplexer _connMultiplexer = ConnectionMultiplexer.Connect(con, config =>
              {
                  config.Password = "123456";
              });

            //redis 哨兵配置
            ConfigurationOptions sentinelOptions = new ConfigurationOptions();
            string sentinelStrs = "192.168.0.168:26379,192.168.0.168:26380,192.168.0.168:26381";
            var IpArray = sentinelStrs.Split(",");
            foreach (var item in IpArray)
            {
                sentinelOptions.EndPoints.Add(item);
            }
            sentinelOptions.TieBreaker = "";
            sentinelOptions.CommandMap = CommandMap.Sentinel;
            sentinelOptions.AbortOnConnectFail = true;
            // Connect!
            ConnectionMultiplexer sentinelConnection = ConnectionMultiplexer.Connect(sentinelOptions);
            // 哨兵监控主机配置
            ConfigurationOptions redisServiceOptions = new ConfigurationOptions();
            redisServiceOptions.ServiceName = "local-master";//master名称
            redisServiceOptions.Password = "123456";  //master访问密码
            redisServiceOptions.AbortOnConnectFail = true;
            redisServiceOptions.AllowAdmin = true;
            _connMultiplexer = sentinelConnection.GetSentinelMasterConnection(redisServiceOptions);

            IDatabase database = _connMultiplexer.GetDatabase();
            //获取学生
            bool exists = database.HashExists(HashKey, Prefix + userId);
            if (exists)
            {
                string result = database.HashGet(HashKey, Prefix + userId);
                //手动释放资源
                _connMultiplexer.Dispose();
                sentinelConnection.Dispose();
                return Ok(result);
            }
            //如果没有 添加学生 做为测试 
            int studentId = Random.Shared.Next(1000, 99999);
            Student student = new Student { Id = studentId, Name = "小李" };
            database.HashSet(HashKey, Prefix + studentId, JsonConvert.SerializeObject(student));

            //手动释放资源
            _connMultiplexer.Dispose();
            sentinelConnection.Dispose();
            return Ok(student);
        }
        /// <summary>
        /// StackExchange 哨兵有密码
        /// </summary>
        /// <returns></returns>
        [HttpGet("StackExchangeForPassWord/{userId}")]
        public ActionResult StackExchangeForPassWord([FromRoute] string userId)
        {

            //redis 集群配置集群有密码
            string con = "192.168.0.168:6379,192.168.0.168:6380,192.168.0.168:6381";
            ConnectionMultiplexer _connMultiplexer = ConnectionMultiplexer.Connect(con, config =>
            {
                config.Password = "123456";
            });


            //redis 哨兵配置
            ConfigurationOptions sentinelOptions = new ConfigurationOptions();
            string sentinelStrs = "192.168.0.168:26379,192.168.0.168:26380,192.168.0.168:26381";
            var IpArray = sentinelStrs.Split(",");
            foreach (var item in IpArray)
            {
                sentinelOptions.EndPoints.Add(item);
            }
            sentinelOptions.TieBreaker = "";
            sentinelOptions.CommandMap = CommandMap.Sentinel;
            sentinelOptions.AbortOnConnectFail = true;
            sentinelOptions.Password = "123456";
            // Connect!
            ConnectionMultiplexer sentinelConnection = ConnectionMultiplexer.Connect(sentinelOptions);
            // 哨兵监控主机配置
            ConfigurationOptions redisServiceOptions = new ConfigurationOptions();
            redisServiceOptions.ServiceName = "local-master";//master名称
            redisServiceOptions.Password = "123456";  //master访问密码
            redisServiceOptions.AbortOnConnectFail = true;
            redisServiceOptions.AllowAdmin = true;
            _connMultiplexer = sentinelConnection.GetSentinelMasterConnection(redisServiceOptions);

            IDatabase database = _connMultiplexer.GetDatabase();
            //获取学生
            bool exists = database.HashExists(HashKey, Prefix + userId);
            if (exists)
            {
                string result = database.HashGet(HashKey, Prefix + userId);
                //手动释放资源
                _connMultiplexer.Dispose();
                sentinelConnection.Dispose();
                return Ok(result);
            }
            //如果没有 添加学生 做为测试 
            int studentId = Random.Shared.Next(1000, 99999);
            Student student = new Student { Id = studentId, Name = "小李" };
            database.HashSet(HashKey, Prefix + studentId, JsonConvert.SerializeObject(student));
            //手动释放资源
            _connMultiplexer.Dispose();
            sentinelConnection.Dispose();
            return Ok(student);
        }


        /// <summary>
        /// Csredis 哨兵无密码
        /// </summary>
        /// <returns></returns>
        [HttpGet("CsredisNoPassWord/{userId}")]
        public async Task<ActionResult> CsredisNoPassWord([FromRoute] string userId)
        {
            using var csredis = new CSRedisClient("local-master,password=123456",
                 new string[] { "192.168.0.168:26379", "192.168.0.168:26380", "192.168.0.168:26381" });
            if (await csredis.HExistsAsync(HashKey, Prefix + userId))
            {
                Student result = csredis.HGet<Student>(HashKey, Prefix + userId);
                return Ok(result);
            }
            int studentId = Random.Shared.Next(1000, 99999);
            Student student = new Student { Id = studentId, Name = "小李" };
            csredis.HSet(HashKey, Prefix + studentId, student);
            return Ok(student);
        }

        /// <summary>
        /// Csredis 哨兵有密码
        /// </summary>
        /// <returns></returns>
        [HttpGet("CsredisForPassWord")]
        public ActionResult CsredisForPassWord()
        {
            return Ok();
        }

    }
}

  

以上代码写的简陋 用于测试连接 后面需要 封装 要注意 用释放资源 using 

  测试的hash 结果 

 

posted on 2023-11-21 12:02  是水饺不是水饺  阅读(388)  评论(0)    收藏  举报

导航