亲宝软件园·资讯

展开

surging 社区版本支持.net core 3.1

fanly11 人气: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; }

    }

总结

开源不易,请大家多多支持

 

加载全部内容

相关教程
猜你喜欢
用户评论