Unity3D自学笔记——Photon服务器的后台架构实现(四)

ALI.ARPG.Domain
实现ICommand, ICommandHandler, IValidateHandler的一系列类
这里写图片描述

public class UserRegisterCommand : ICommand
    {
        public string Name;
        public string Password;
    }
public class UserRegisterHandler : ICommandHandler<UserRegisterCommand>
    {
        private readonly AccountRepository accountRepository;
        private UnitOfWork unitOfWork;

        public UserRegisterHandler()
        {
            unitOfWork = new UnitOfWork();
            accountRepository = new AccountRepository(unitOfWork.Session);
        }

        public ICommandResult Excute(UserRegisterCommand command)
        {
        //这里用了AutoMapper,做了 Entity <-->ICommand之间的映射,AutoMapper的配置在Server层
            AccountEntity account = Mapper.Map<AccountEntity>(command);

            accountRepository.Add(account);
            //通过unitOfWork将数据处理打包执行
            unitOfWork.Commit();
            return new CommandResult(true);
        }
    }
public IEnumerable<ValidationResult> Validate(UserRegisterCommand command)
        {
            //TODO 用户注册验证逻辑
            //e.g.:
            //if (string.IsNullOrEmpty(command.Name))
            //{
            //    yield return new ValidationResult("Name", "必须输入用户名");
            //}
            return null;
        }

ALI.ARPG.Server
这里写图片描述

AutoMapper
配置,这里用的是AutoMapper5.0,稍微和前面的版本有些区别

public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile(new ViewModelToDomainMappingProfile());
                x.AddProfile(new DomainToViewModelMappingProfile());
            });
        }
    }

Entity -> Command

public class DomainToViewModelMappingProfile : Profile
    {
        public DomainToViewModelMappingProfile()
        {
            this.CreateMap<UserRegisterCommand, AccountEntity>();
        }
    }

Command -> Entity

public class ViewModelToDomainMappingProfile : Profile
    { 
        public ViewModelToDomainMappingProfile()
        {
            this.CreateMap<AccountEntity, UserRegisterCommand>();
        }
    }

Application
Photon Server 的Host 类

public class Application : ApplicationBase
    {
        private static readonly ILogger log = ExitGames.Logging.LogManager.GetCurrentClassLogger();
        protected override PeerBase CreatePeer(InitRequest initRequest)
        {
            return new AliPeer(initRequest.Protocol, initRequest.PhotonPeer);
        }

        protected override void Setup()
        {
            try { 
            //AutoMapper
            AutoMapperConfiguration.Configure();
            //Log
            ExitGames.Logging.LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);
            GlobalContext.Properties["Photon:ApplicationLogPath"] = Path.Combine(this.ApplicationRootPath, "log");
            GlobalContext.Properties["LogFileName"] = "ALI" + this.ApplicationName;
            XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(this.BinaryPath, "log4net.config")));

            log.Debug("服务器启动成功");
            }
            catch(Exception ex)
            {
                log.Debug(ex.Message);
            }
        }

        protected override void TearDown()
        {
            log.Debug("服务器关闭");
        }
    }

AliPeer
Photon Server 的Peer类,和客户端进行交互的类

public class AliPeer : PeerBase
    {
        private static readonly ILogger log = ExitGames.Logging.LogManager.GetCurrentClassLogger();
        private ICommandBus commandBus;
        public AliPeer(IRpcProtocol protocol, IPhotonPeer peer) : base(protocol, peer) {
            commandBus = new CommandBus();
        }
        protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
        {

        }

        protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
        {
            if (AliPeer.log.IsDebugEnabled)
            {
                AliPeer.log.DebugFormat("OnOperationRequest. Code={0}", operationRequest.OperationCode);
            }
            //根据OpreationCode 去调度具体的方法
            switch (operationRequest.OperationCode)
            {
                case (byte)OperationCode.Register:
                    HandleRegisterOperation(operationRequest, sendParameters);
                    break;
                case (byte)OperationCode.Login:
                    HandleLoginrOperation(operationRequest, sendParameters);
                    break;
                default:
                    break;
            }
        }

        protected virtual void HandleRegisterOperation(OperationRequest operationRequest, SendParameters sendParameters)
        {
        //获取客户端的消息,将Json转化为实体,用到LitJson.dll
            object json;
            operationRequest.Parameters.TryGetValue(operationRequest.OperationCode, out json);
            AccountEntity account = JsonMapper.ToObject<AccountEntity>(json.ToString());
            //AutoMapper, Entity -> Command
            var command = Mapper.Map<AccountEntity, UserRegisterCommand>(account);
            //通过CommandBus反射调用IValidateHandler, 执行消息验证
            IEnumerable<ValidationResult> errors = commandBus.Validate(command);
            OperationResponse response = new OperationResponse();

            if(errors != null && errors.ToList().Count > 0)
            {
                response.ReturnCode = (short)ReturnCode.Error;
            }
            else
            {
                //通过CommandBus反射调用ICommandHandler, 执行Submit
                var result = commandBus.Submit(command);
                if (result.Success)
                {
                    response.ReturnCode = (short)ReturnCode.Sucess;
                }
                else
                {
                    response.ReturnCode = (short)ReturnCode.Faild;
                }
            }
            //返回客户端处理结果
            SendOperationResponse(response, sendParameters);
        }

        protected virtual void HandleLoginrOperation(OperationRequest operationRequest, SendParameters sendParameters)
        {

        }
    }

OK 到此,服务端基本框架已完成,还可以加入AOP进行日志处理

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值