Redis Master/Slave 实践

时间:2024-04-03 23:34:44

本次我们将模拟 Master(1) + Slave(4) 的场景,并通过ASP.NET WEB API进行数据的提交及查询,监控 Redis Master/Slave 数据分发情况,只大致概述,不会按照step by step的方式一一列举.

API List:

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

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

  

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

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

  

AutoMapper 自动转换Request DTO 与 DomainEntity

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 配置介绍:

Step1: 下载Redis

Step2: 分别创建如下图所示目录 data_1~data_4,redis_1.config~redis_4.config

data_1,redis_1.config 为Master 存储目录及配置文件

data_2~data_4,redis_2.config~ redis_4.config为Slave 存储目录及配置文件

Redis Master/Slave 实践

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

port:6380~6381

dir:./data_2/~./data_4/

slaveof localhost 6379

Redis Master/Slave 实践

Redis Master/Slave 实践

Redis Desktop Manager 监控:

Redis Master/Slave 实践