Orleans在.net core的开发

 

 

 

Orleans在.net core的开发_第1张图片

 

 Goods 服务 启动

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Entity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Serialization;

namespace Order
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            
            int silePort = 11113; int gatewayPort = 30000; int mainSiloPort = 11111;

           
            //启动Host
            StartAsyncHost(silePort, gatewayPort, mainSiloPort, services);

            //启动本地服务
            StartAsyncClient(mainSiloPort, gatewayPort, silePort, services).Wait();


            services.ServerInjectionADD();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }

        /// 
        /// 在本地启动一个Host
        /// 
        /// 
        async Task StartAsyncHost(int silePort, int gatewayPort, int mainSiloPort, IServiceCollection servicesCollection)
        {
            var builder = new SiloHostBuilder()

                   .Configure(d => { d.SerializationProviders.Add(typeof(ProtobufSerializer).GetTypeInfo()); d.FallbackSerializationProvider = typeof(ProtobufSerializer).GetTypeInfo(); })
                    .UseDevelopmentClustering(new IPEndPoint(IPAddress.Loopback, mainSiloPort))
                    .ConfigureEndpoints(siloPort: silePort, gatewayPort: gatewayPort)

                    .Configure(options =>
                    {
                        //ClusterId为集群名称 相同的名称才能被分配到一个集群中
                        options.ClusterId = "dev";
                        //当前服务的名称  
                        options.ServiceId = "GoodsServer";
                    })
                    .AddStartupTask(
                      async (IServiceProvider services, CancellationToken cancellation) =>
                      {
                          var grainFactory = services.GetRequiredService();

                          //var grain = grainFactory.GetGrain(0);
                          //注册本机服务

                      })
                     //注入打印消息的入口
                     .ConfigureLogging(logging => logging.AddConsole());

            //进行构建 
            var host = builder.Build();
            //启动服务
            await host.StartAsync();
            Console.WriteLine("服务启动成功");
            return host;
        }
        async Task StartAsyncClient(int mainSiloProt, int gatewayProt, int siloProt, IServiceCollection servicesCollection)
        {
            IClusterClient client = new ClientBuilder()
                 .Configure(d => { d.SerializationProviders.Add(typeof(ProtobufSerializer).GetTypeInfo()); d.FallbackSerializationProvider = typeof(ProtobufSerializer).GetTypeInfo(); })
                 //与主简仓进行连接
                 .UseStaticClustering(new IPEndPoint[] { new IPEndPoint(GetInternalIp(), gatewayProt) })
               .Configure(options =>
               {
                   options.ClusterId = "dev";
                   options.ServiceId = "GoodsClient";
               })

           //配置刷新简仓的时间 一般来说不会这么短
           //.Configure(d => d.GatewayListRefreshPeriod = TimeSpan.FromSeconds(5))
           .ConfigureLogging(logging => logging.AddConsole()).Build();
           await client.Connect();
            Console.WriteLine("Orleans客户端已经启动");
            servicesCollection.AddSingleton(client);

        }

        public static IPAddress GetInternalIp()
        {
            IPHostEntry myEntry = Dns.GetHostEntry(Dns.GetHostName());
            return myEntry.AddressList.FirstOrDefault(e => e.AddressFamily.ToString().Equals("InterNetwork"));

        }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Orleans;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Order
{
    /// 
    /// 注入本地服务
    /// 
    public static class ServerInjection
    {
        /// 
        /// 服务注入  在最后使用
        /// 
        /// 
        public static void ServerInjectionADD(this IServiceCollection services) {
           


            services.AddSingleton();




            //引用对象留在最后
            serviceProvider = services.BuildServiceProvider();
        }

        public static ServiceProvider serviceProvider { get; set; }

        public static T GetServer(this Controller controller) where T:class, IGrainWithIntegerKey
        {
           var TService = serviceProvider.GetService();
            if (TService==null)
            {
                var client = serviceProvider.GetService();
                if (client==null)
                {
                    throw new Exception("客户端没有启动 或者没有被注入");
                }
                TService = client.GetGrain(0);
                if (TService==null)
                {
                    throw new Exception("没有找到该类型" + TService.GetType());
                }
                return TService;
            }
            return TService;
        }
    }
    
}

 

截图

Goods服务

Orleans在.net core的开发_第2张图片

Order服务

Orleans在.net core的开发_第3张图片

 

GitHub地址:

Demo下载

转载于:https://www.cnblogs.com/AnAng/p/9915670.html

你可能感兴趣的:(Orleans在.net core的开发)