1. 程式人生 > >surging 社群版本支援.net core 3.1

surging 社群版本支援.net core 3.1

簡介

surging 經過兩年多的研發,微服務引擎已經略有雛形,也承蒙各位的厚愛, GitHub上收穫了將近2800星,fork 811,付費使用者企業也有十幾家,還有諮詢培訓,

在2020年,我們將依靠社群的力量,去完善社群版本,更會花更多的精力去維護好付費使用者,大家一起把surging 的社群建設好,還有十幾天就要過年,大家可以加入surging唯一官方群:615562965, 過年的時候會和往常一樣發紅包,而且不少哦。讓我們過年狂歡起來。

 surging 將會有自己的官方站,作者正在用VuePress進行研發,在不久的日子將會和大家見面

新功能簡述

1.GRPC協議支援:

新增介面,將ServerCallContext引數的預設值設定為null。 程式碼如下:

 

using Greet;
using Grpc.Core;
using Surging.Core.CPlatform.Ioc;
using Surging.Core.CPlatform.Runtime.Server.Implementation.ServiceDiscovery.Attributes;
using System.Threading.Tasks;

namespace Surging.IModuleServices.Common
{
    [ServiceBundle("api/{Service}/{Method}")]
    public  interface IGreeterService : IServiceKey
    {
        Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context=null);
    }
}

新增GreeterBehavior,程式碼如下

using Greet;
using Surging.Core.CPlatform.Ioc;

namespace Surging.Modules.Common.GreeterServices
{
    public  partial class GreeterBehavior : Greeter.GreeterBase,IServiceBehavior
    {
        
    }
}

 新增業務程式碼,程式碼如下:

using Greet;
using Grpc.Core;
using Surging.IModuleServices.Common;
using Surging.Modules.Common.GreeterServices;

using System.Threading.Tasks;

namespace Surging.Modules.Common.Domain
{
    public class GreeterService: GreeterBehavior, IGreeterService
    {
        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "Hello " + request.Name
            });
        }
    }
}

客戶端GRPC呼叫,程式碼如下

using Greet;
using Grpc.Core;
using System;

namespace GrpcService1
{
    public class Program
    {
        public static void Main(string[] args)
        {
           var  channel = new Channel("127.0.0.1", 95, ChannelCredentials.Insecure);
           var client = new Greeter.GreeterClient(channel);
            var result = client.SayHello(new HelloRequest
            {
                Name = "fanly"
            });

            Console.WriteLine("grpc Client Call SayHello():" + result); 
            Console.ReadKey();
        } 
    }
}

2.支援WorkService後臺託管守護程式

引擎支援WorkService後臺服務,可以支援RPC遠端呼叫開啟,關閉,新增任務處理,程式碼如下:

新增介面程式碼如下:

   [ServiceBundle("Background/{Service}")]
    public interface IWorkService : IServiceKey
    {
        Task<bool> AddWork(Message message);

         Task StartAsync();

        Task StopAsync();
    }

然後需要繼承BackgroundServiceBehavior,而且服務的生命週期設定為ISingleInstance

 public class WorkService : BackgroundServiceBehavior, IWorkService, ISingleInstance
    {
        private readonly ILogger<WorkService> _logger;
        private   readonly Queue<Message> _queue = new Queue<Message>();
        private readonly IServiceProxyProvider _serviceProxyProvider;
        private CancellationToken _token;

        public WorkService(ILogger<WorkService> logger, IServiceProxyProvider serviceProxyProvider)
        {
            _logger = logger;
            _serviceProxyProvider = serviceProxyProvider;
        }

        public  Task<bool> AddWork(Message message)
        {
            _queue.Enqueue(message);
            return Task.FromResult(true);
        }

        protected override async  Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                _token = stoppingToken;
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                _queue.TryDequeue(out Message message);
                if (message != null)
                {
                    var result = await _serviceProxyProvider.Invoke<object>(message.Parameters, message.RoutePath, message.ServiceKey);
                    _logger.LogInformation("Invoke Service at: {time},Invoke result:{result}", DateTimeOffset.Now, result);
                }
                if (!_token.IsCancellationRequested)
                    await Task.Delay(1000, stoppingToken);
            }
            catch (Exception ex){
                _logger.LogError("WorkService execute error, message:{message} ,trace info:{trace} ", ex.Message, ex.StackTrace);
            }
        }

        public async Task StartAsync()
        {
            if (_token.IsCancellationRequested)
            { 
                await base.StartAsync(_token);
            }
        }

        public async Task StopAsync()
        {
            if (!_token.IsCancellationRequested)
            {
               await  base.StopAsync(_token);
            }
        }
    }

3.支援特性驗證

支援介面特性驗證,程式碼如下

   [ServiceBundle("api/{Service}/{Method}")]
    //[ServiceBundle("api/{Service}")]
    //[ServiceBundle("api/{Service}/{Method}/test")]
    //[ServiceBundle("api/{Service}/{Method}/test",false)]
    public interface IUserService: IServiceKey
    {
        /// <summary>
        /// 獲取使用者姓名
        /// </summary>
        /// <param name="id">使用者編號</param>
        /// <returns></returns>
        [ServiceRoute("{id}")]
        Task<string> GetUserName([Validate] [Range(1, 10, ErrorMessage = "只能為1到10")] int id);


 /// <summary>
        /// 獲取使用者
        /// </summary>
        /// <param name="user">使用者模型</param>
        /// <returns></returns>
        [Command(Strategy = StrategyType.Injection, Injection = @"return
new Surging.IModuleServices.Common.Models.UserModel
         {
            Name=""fanly"",
            Age=19
         };", RequestCacheEnabled = true, InjectionNamespaces = new string[] { "Surging.IModuleServices.Common" })]
        [InterceptMethod(CachingMethod.Get, Key = "GetUser_id_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis, Time = 480)]
        [Validate]
        Task<UserModel> GetUser(UserModel user);
          

}

支援模型特性驗證,介面方法一定要新增 [Validate]特性,要不然不會進行驗證,程式碼如下

   [ProtoContract]
    public class UserModel
    {

        [ProtoMember(1)]
        [CacheKey(1)]
        public int UserId { get; set; }

        [ProtoMember(2)]
        public string Name { get; set; }

        [ProtoMember(3)]
        [Range(0, 150, ErrorMessage = "年齡只能在0到150歲之間")]
        public int Age { get; set; }

        [ProtoMember(4)]
        [Range(0, 1, ErrorMessage = "性別只能選男或女")]
        public Sex Sex { get; set; }

    }

總結

開源不易,請大家多多支援