星尘工厂自动注册,简化使用成本

This commit is contained in:
智能石头 2021-03-17 22:11:28 +08:00
parent cf98a99529
commit c0144439f1
12 changed files with 258 additions and 45 deletions

View File

@ -0,0 +1,53 @@
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server.Features;
using NewLife;
using NewLife.Reflection;
using Stardust;
using Stardust.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>星尘工厂扩展</summary>
public static class StarFactoryExtensions
{
/// <summary>添加星尘</summary>
/// <param name="services"></param>
/// <param name="appId"></param>
/// <returns></returns>
public static StarFactory AddStardust(this IServiceCollection services, String appId)
{
var star = new StarFactory(appId);
services.AddSingleton(star);
services.AddSingleton(star.Tracer);
services.AddSingleton(star.Config);
services.AddHostedService<StarService>();
return star;
}
/// <summary>发布服务到注册中心</summary>
/// <param name="app"></param>
/// <param name="serviceName">服务名</param>
/// <param name="tag"></param>
/// <returns></returns>
public static IApplicationBuilder PublishService(this IApplicationBuilder app, String serviceName, String tag = null)
{
var star = app.ApplicationServices.GetRequiredService<StarFactory>();
if (star == null) throw new InvalidOperationException("未注册StarFactory需要AddStardust注册。");
var feature = app.ServerFeatures.Get<IServerAddressesFeature>();
var addrs = feature?.Addresses.Join();
if (addrs.IsNullOrEmpty()) return app;
//XTrace.WriteLine("{0}", feature?.Addresses.Join());
if (serviceName.IsNullOrEmpty()) serviceName = AssemblyX.Entry.Name;
star.Dust.PublishAsync(serviceName, addrs, tag).Wait();
return app;
}
}
}

View File

@ -0,0 +1,43 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Hosting;
using NewLife;
using NewLife.Log;
using NewLife.Reflection;
namespace Stardust.Extensions
{
internal class StarService : IHostedService
{
private readonly StarFactory _starFactory;
private readonly IFeatureCollection _applicationBuilder;
public StarService(StarFactory starFactory, IFeatureCollection applicationBuilder)
{
_starFactory = starFactory;
_applicationBuilder = applicationBuilder;
}
public Task StartAsync(CancellationToken cancellationToken)
{
var feature = _applicationBuilder.Get<IServerAddressesFeature>();
var addrs = feature?.Addresses.Join();
if (!addrs.IsNullOrEmpty())
{
var serviceName = _starFactory.ServiceName;
if (serviceName.IsNullOrEmpty()) serviceName = AssemblyX.Entry.Name;
// 发布服务到星尘注册中心
XTrace.WriteLine("发布服务[{0}]到星尘注册中心。", serviceName);
_starFactory.Dust.PublishAsync(serviceName, addrs).Wait();
}
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}

View File

@ -0,0 +1,66 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net5.0</TargetFrameworks>
<AssemblyTitle>星尘分布式服务框架</AssemblyTitle>
<Description>星尘,分布式服务框架。分布式资源调度,服务自动注册和发现,负载均衡,动态伸缩,故障转移,性能监控。</Description>
<Company>新生命开发团队</Company>
<Copyright>©2002-2021 NewLife</Copyright>
<Version>1.4.2021.0316-beta2</Version>
<FileVersion>1.4.2021.0316</FileVersion>
<AssemblyVersion>1.4.*</AssemblyVersion>
<Deterministic>false</Deterministic>
<OutputPath>..\Bin</OutputPath>
<DocumentationFile>$(OutputPath)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<PropertyGroup>
<PackageId>NewLife.$(AssemblyName)</PackageId>
<Authors>$(Company)</Authors>
<ProjectUrl>https://github.com/NewLifeX</ProjectUrl>
<PackageIcon>leaf.png</PackageIcon>
<RepositoryUrl>https://github.com/NewLifeX/Stardust</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageTags>新生命团队;X组件;NewLife;$(AssemblyName)</PackageTags>
<PackageReleaseNotes>星尘监控用法标准化</PackageReleaseNotes>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='netstandard2.0'">
<DefineConstants>$(DefineConstants);NETSTANDARD2_0;__CORE__</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net5.0'">
<DefineConstants>$(DefineConstants);NET50;__CORE__</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net40'">
<DefineConstants>$(DefineConstants);__WIN__;NET4</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net45'">
<DefineConstants>$(DefineConstants);__WIN__;NET45</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net5.0'">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Stardust\Stardust.csproj" />
</ItemGroup>
</Project>

View File

@ -1,9 +1,7 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using NewLife.Log;
using Stardust.Data;
namespace Stardust.Server
{
@ -13,9 +11,6 @@ namespace Stardust.Server
{
XTrace.UseConsole();
// 异步初始化
Task.Run(InitAsync);
CreateWebHostBuilder(args).Build().Run();
}
@ -31,20 +26,5 @@ namespace Stardust.Server
return builder;
}
private static void InitAsync()
{
// 配置
var set = NewLife.Setting.Current;
if (set.IsNew)
{
set.DataPath = "../Data";
set.Save();
}
// 初始化数据库
var n = App.Meta.Count;
//AppStat.Meta.Session.Dal.Db.ShowSQL = false;
}
}
}

View File

@ -1,8 +1,10 @@
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@ -10,6 +12,7 @@ using Microsoft.Extensions.Hosting;
using NewLife;
using NewLife.Cube.WebMiddleware;
using NewLife.Log;
using Stardust.Data;
using Stardust.Server.Common;
using Stardust.Server.Services;
using XCode.DataAccessLayer;
@ -65,6 +68,9 @@ namespace Stardust.Server
services.AddHostedService<NodeOnlineService>();
services.AddHostedService<ApolloService>();
// 异步初始化
Task.Run(InitAsync);
services.AddControllers()
.AddJsonOptions(options =>
{
@ -102,6 +108,28 @@ namespace Stardust.Server
{
endpoints.MapControllers();
});
var feature = app.ServerFeatures.Get<IServerAddressesFeature>();
//foreach (var item in feature.Addresses)
//{
// XTrace.WriteLine("{0}", item);
//}
XTrace.WriteLine("{0}", feature?.Addresses.Join());
}
private static void InitAsync()
{
// 配置
var set = NewLife.Setting.Current;
if (set.IsNew)
{
set.DataPath = "../Data";
set.Save();
}
// 初始化数据库
var n = App.Meta.Count;
//AppStat.Meta.Session.Dal.Db.ShowSQL = false;
}
}
}

View File

@ -1,9 +1,7 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using NewLife.Log;
using Stardust.Data;
namespace Stardust.Web
{
@ -13,29 +11,11 @@ namespace Stardust.Web
{
XTrace.UseConsole();
// 异步初始化
Task.Run(InitAsync);
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(String[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
private static void InitAsync()
{
// 配置
var set = NewLife.Setting.Current;
if (set.IsNew)
{
set.DataPath = "../Data";
set.Save();
}
// 初始化数据库
var n = App.Meta.Count;
//AppStat.Meta.Session.Dal.Db.ShowSQL = false;
}
}
}

View File

@ -51,6 +51,7 @@
<ItemGroup>
<ProjectReference Include="..\Stardust.Data\Stardust.Data.csproj" />
<ProjectReference Include="..\Stardust.Extensions\Stardust.Extensions.csproj" />
<ProjectReference Include="..\Stardust\Stardust.csproj" />
</ItemGroup>

View File

@ -1,10 +1,14 @@
using Microsoft.AspNetCore.Builder;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NewLife;
using NewLife.Cube;
using NewLife.Log;
using Stardust.Data;
using Stardust.Server.Services;
using XCode.DataAccessLayer;
@ -18,7 +22,7 @@ namespace Stardust.Web
public void ConfigureServices(IServiceCollection services)
{
var star = new StarFactory("StarWeb");
var star = services.AddStardust("StarWeb");
var tracer = star.Tracer;
services.AddSingleton<ITracer>(tracer);
@ -41,6 +45,9 @@ namespace Stardust.Web
// 后台服务。数据保留,定时删除过期数据
services.AddHostedService<ApolloService>();
// 异步初始化
Task.Run(InitAsync);
services.AddControllersWithViews();
services.AddCube();
}
@ -61,6 +68,24 @@ namespace Stardust.Web
name: "default",
pattern: "{controller=CubeHome}/{action=Index}/{id?}");
});
//// 发布服务到星尘注册中心
//app.PublishService("StarWeb");
}
private static void InitAsync()
{
// 配置
var set = NewLife.Setting.Current;
if (set.IsNew)
{
set.DataPath = "../Data";
set.Save();
}
// 初始化数据库
var n = App.Meta.Count;
//AppStat.Meta.Session.Dal.Db.ShowSQL = false;
}
}
}

View File

@ -5,6 +5,7 @@ using System.Net.Http;
using System.Threading.Tasks;
using NewLife;
using NewLife.Log;
using NewLife.Reflection;
using NewLife.Remoting;
using NewLife.Threading;
using NewLife.Web;
@ -145,9 +146,33 @@ namespace Stardust
/// <summary>发布</summary>
/// <param name="service"></param>
/// <returns></returns>
public async Task<Boolean> PublishAsync(PublishServiceInfo service)
public async Task<Object> PublishAsync(PublishServiceInfo service)
{
return await PostAsync<Boolean>("Publish", service);
return await PostAsync<Object>("Publish", service);
}
/// <summary>发布</summary>
/// <param name="serviceName">服务名</param>
/// <param name="address">服务地址</param>
/// <param name="tag">特性标签</param>
/// <returns></returns>
public async Task<Object> PublishAsync(String serviceName, String address, String tag = null)
{
var ip = NetHelper.MyIP();
var p = Process.GetCurrentProcess();
var asmx = AssemblyX.Entry;
var info = new PublishServiceInfo
{
ServiceName = serviceName,
Address = address,
Tag = tag,
Client = $"{ip}@{p.Id}",
Version = asmx.Version,
};
return await PublishAsync(info);
}
/// <summary>消费</summary>

View File

@ -2,6 +2,7 @@
using NewLife;
using NewLife.Configuration;
using NewLife.Log;
using NewLife.Reflection;
using NewLife.Remoting;
using Stardust.Monitors;
@ -19,6 +20,9 @@ namespace Stardust
/// <summary>应用密钥</summary>
public String Secret { get; set; }
/// <summary>服务名</summary>
public String ServiceName { get; set; }
#endregion
#region
@ -27,6 +31,8 @@ namespace Stardust
/// <returns></returns>
public StarFactory(String appId)
{
if (appId.IsNullOrEmpty()) appId = AssemblyX.Entry.Name;
AppId = appId;
//var set = Setting.Current;
//Server = set.Server;

View File

@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFrameworks>net45;netstandard2.0;net5.0</TargetFrameworks>
<AssemblyName>Stardust</AssemblyName>
<AssemblyTitle>星尘分布式服务框架</AssemblyTitle>
<AssemblyTitle>星尘分布式服务扩展</AssemblyTitle>
<Description>星尘,分布式服务框架。分布式资源调度,服务自动注册和发现,负载均衡,动态伸缩,故障转移,性能监控。</Description>
<Company>新生命开发团队</Company>
<Copyright>©2002-2021 NewLife</Copyright>

View File

@ -35,6 +35,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StarAgentTool", "StarAgentT
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StarGateway", "StarGateway\StarGateway.csproj", "{94CCBB9E-628D-4381-8E2C-DF349EFD204F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Stardust.Extensions", "Stardust.Extensions\Stardust.Extensions.csproj", "{28C1DC01-2A89-47B6-8E9D-6351C12722AC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -81,6 +83,10 @@ Global
{94CCBB9E-628D-4381-8E2C-DF349EFD204F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94CCBB9E-628D-4381-8E2C-DF349EFD204F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94CCBB9E-628D-4381-8E2C-DF349EFD204F}.Release|Any CPU.Build.0 = Release|Any CPU
{28C1DC01-2A89-47B6-8E9D-6351C12722AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{28C1DC01-2A89-47B6-8E9D-6351C12722AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{28C1DC01-2A89-47B6-8E9D-6351C12722AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{28C1DC01-2A89-47B6-8E9D-6351C12722AC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE