Redis Master/Slave 實踐

本次咱們將模擬 Master(1) + Slave(4) 的場景,並經過ASP.NET WEB API進行數據的提交及查詢,監控 Redis Master/Slave 數據分發狀況,只大體概述,不會按照step by step的方式一一列舉.javascript

 

API List:java

[POST]:http://localhost:53964/api/persons
Accept:application/json ,Content-Type:application/jsonredis

{
    "Id": 2,
    "Name": "Leo.J.Liu"
}

  

[GET]:http://localhost:53964/api/persons/1
Accept:application/json ,Content-Type:application/jsonjson

{
    "Id": 2,
    "Name": "Leo.J.Liu"
}

  

AutoMapper 自動轉換Request DTO 與 DomainEntity
api

private readonly IPersonService personService;

public PersonsController(IPersonService personService)
{
     this.personService = personService;
}

  

 public HttpResponseMessage GetPerson(int id)
        {
            var person = personService.GetPersonById(id);
            if (person == null)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent(string.Format("No person with ID = {0}", id)),
                    ReasonPhrase = "Person ID Not Found"
                };
                throw new HttpResponseException(resp);
            };
            return Request.CreateResponse(HttpStatusCode.OK, person);
        }

  

public HttpResponseMessage AddPerson([FromBody] PersonRequestDto personDto)
        {
            Person person = Mapper.Map<PersonRequestDto,Person>(personDto);
            var persons = personService.AddPerson(person);
            return Request.CreateResponse(HttpStatusCode.OK, persons);
        }
Application_Start 中完成AutoMapper註冊
public class AutoMapperConfig
    {
        public static void RegisterMappings()
        {
            Mapper.Initialize(c =>
            {
                c.CreateMap<PersonRequestDto,Person>().ForMember(s=>s.UserAge,d=>d.MapFrom(e=>e.Age));
            });
        }
    }

採用StackExchange.Redis 做爲Redis的Client,其中(6379爲Master,提供寫操做),(6380~6382爲Slave,提供查詢操做)
public  class RedisService<T> where T : new()
    {
        public static ConfigurationOptions QueryConfig = new ConfigurationOptions
        {
            EndPoints =
                {
                    { "localhost", 6380 },
                    { "localhost", 6381 },
                    { "localhost", 6382 }
                },
        };

        public static ConfigurationOptions SaveConfig = new ConfigurationOptions
        {
            EndPoints =
                {
                    { "localhost", 6379 }
                },
        };

        public static T Get(string type,string key)
        {
            ConnectionMultiplexer redis =
                ConnectionMultiplexer.Connect(QueryConfig);

            IDatabase db = redis.GetDatabase();

            string value = db.StringGet(string.Format("{0}:{1}",type,key));

            return JsonConvert.DeserializeObject<T>(value);
        }


        public static bool Save(string type, string key, T reqDto)
        {
            ConnectionMultiplexer redis =
                ConnectionMultiplexer.Connect(SaveConfig);

            IDatabase db = redis.GetDatabase();

            string json = JsonConvert.SerializeObject(reqDto);

            return db.StringSet(string.Format("{0}:{1}", type, key), json);
        }
    }
SimpleInjector 做爲Ioc Container
public static class SimpleInjectorWebApiInitializer
    {
        public static void Initialize()
        {
            var container = new Container();
            
            InitializeContainer(container);

            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
       
            container.Verify();
            
            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
        }
     
        private static void InitializeContainer(Container container)
        {
            container.Register<IPersonService, PersonService>();
            container.Register<IRepository<Person>, PersonRepository>();
        }
    }

  

public class PersonRepository : IRepository<Person>
    {

        public List<Person> GetAll()
        {
            return RedisService<List<Person>>.Get("persons",string.Empty);
        }

        public Person GetById(int id)
        {
            return RedisService<Person>.Get("persons",id.ToString());
        }

        public bool Add(Person reqDto)
        {
            return RedisService<Person>.Save("persons", reqDto.Id.ToString(), reqDto);
        }

        public bool Update(Person reqDto)
        {
            throw new NotImplementedException();
        }

        public bool Remove(Person reqDto)
        {
            throw new NotImplementedException();
        }
    }

  


Redis 配置介紹:app

 

Step1: 下載Redisthis

Step2: 分別建立以下圖所示目錄 data_1~data_4,redis_1.config~redis_4.config3d

data_1,redis_1.config 爲Master 存儲目錄及配置文件orm

data_2~data_4,redis_2.config~ redis_4.config爲Slave 存儲目錄及配置文件blog

 

redis_2.config~ redis_4.config配置說明:

port:6380~6381

dir:./data_2/~./data_4/

slaveof localhost 6379

 

Redis Desktop Manager 監控:

相關文章
相關標籤/搜索