Exemplo n.º 1
0
        public static IHummingbirdHostBuilder AddEventBus(this IHummingbirdHostBuilder hostBuilder, Action <IHummingbirdEventBusHostBuilder> setup)
        {
            var builder = new HummingbirdEventBusHostBuilder(hostBuilder.Services);;

            setup(builder);
            return(hostBuilder);
        }
        public static IHummingbirdHostBuilder AddOpenTracing(this IHummingbirdHostBuilder hostBuilder, Action <IHummingbirdOpenTracingBuilder> action)
        {
            var builder = new HummingbirdOpenTracingBuilder(hostBuilder.Services);

            action(builder);
            return(hostBuilder);
        }
Exemplo n.º 3
0
        public static IHummingbirdHostBuilder AddResilientHttpClient(this IHummingbirdHostBuilder hostBuilder, Action <ResilientHttpClientConfigOption> setupConfig = null)
        {
            hostBuilder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            hostBuilder.Services.AddSingleton <IHttpClientFactory, ResilientHttpClientFactory>(sp =>
            {
                var Configuration       = sp.GetRequiredService <IConfiguration>();
                var logger              = sp.GetRequiredService <ILogger <ResilientHttpClient> >();
                var httpContextAccessor = sp.GetRequiredService <IHttpContextAccessor>();
                var option              = new ResilientHttpClientConfigOption()
                {
                    TimeoutMillseconds              = 1000,
                    RetryCount                      = 3,
                    DurationSecondsOfBreak          = 15,
                    ExceptionsAllowedBeforeBreaking = 10
                };

                if (setupConfig != null)
                {
                    setupConfig(option);
                }

                return(new ResilientHttpClientFactory(logger,
                                                      httpContextAccessor,
                                                      option.TimeoutMillseconds,
                                                      option.ExceptionsAllowedBeforeBreaking,
                                                      option.RetryCount,
                                                      option.DurationSecondsOfBreak));
            });
            hostBuilder.Services.AddSingleton <IHttpClient>(sp => sp.GetService <IHttpClientFactory>().CreateResilientHttpClient());
            return(hostBuilder);
        }
Exemplo n.º 4
0
        public static IHummingbirdHostBuilder AddDistributedLock(this IHummingbirdHostBuilder hostBuilder, Action <Config> action)
        {
            action = action ?? throw new ArgumentNullException(nameof(action));
            var RedisDistributedLock = DistributedLockFactory.Build(action);

            hostBuilder.Services.AddSingleton <IDistributedLock>(RedisDistributedLock);
            return(hostBuilder);
        }
Exemplo n.º 5
0
        public static IHummingbirdHostBuilder AddCache(this IHummingbirdHostBuilder hostBuilder, Action <Hummingbird.Extersions.Cache.RedisConfigurationBuilder> configuration, string CacheRegion = "")
        {
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <object>), sp =>
            {
                return(Hummingbird.Extersions.Cache.CacheFactory.Build <object>(configuration, CacheRegion));
            });

            return(hostBuilder);
        }
Exemplo n.º 6
0
 public static IHummingbirdHostBuilder AddCanal(this IHummingbirdHostBuilder hostBuilder, IConfigurationSection configurationSection)
 {
     hostBuilder.Services.AddSingleton <CanalConfig>(sp =>
     {
         return(configurationSection.Get <CanalConfig>());
     });
     hostBuilder.Services.AddHostedService <CanalClientHostedService>();
     return(hostBuilder);
 }
        public static IHummingbirdHostBuilder AddCache(this IHummingbirdHostBuilder hostBuilder, Action <IHummingbirdCacheConfig> setupOption = null)
        {
            var config = new HummingbirdCacheConfig();

            if (setupOption != null)
            {
                setupOption(config);
            }
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCacheConfig), config);
            hostBuilder.Services.AddSingleton(typeof(ICacheManager <int>), sp =>
            {
                return(GetCacheManager <int>(sp, config.ConfigName));
            });
            hostBuilder.Services.AddSingleton(typeof(ICacheManager <long>), sp =>
            {
                return(GetCacheManager <int>(sp, config.ConfigName));
            });
            hostBuilder.Services.AddSingleton(typeof(ICacheManager <string>), sp =>
            {
                return(GetCacheManager <string>(sp, config.ConfigName));
            });
            hostBuilder.Services.AddSingleton(typeof(ICacheManager <bool>), sp =>
            {
                return(GetCacheManager <bool>(sp, config.ConfigName));
            });
            hostBuilder.Services.AddSingleton(typeof(ICacheManager <object>), sp =>
            {
                return(GetCacheManager <object>(sp, config.ConfigName));
            });

            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <int>), sp => {
                var cacheManager = sp.GetRequiredService <ICacheManager <int> >();
                return(new Hummingbird.Extensions.Cache.HummingbirdCacheManagerCache <int>(cacheManager, config.CacheRegion));
            });
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <long>), sp => {
                var cacheManager = sp.GetRequiredService <ICacheManager <long> >();
                return(new Hummingbird.Extensions.Cache.HummingbirdCacheManagerCache <long>(cacheManager, config.CacheRegion));
            });
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <string>), sp => {
                var cacheManager = sp.GetRequiredService <ICacheManager <string> >();
                return(new Hummingbird.Extensions.Cache.HummingbirdCacheManagerCache <string>(cacheManager, config.CacheRegion));
            });
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <bool>), sp => {
                var cacheManager = sp.GetRequiredService <ICacheManager <bool> >();
                return(new Hummingbird.Extensions.Cache.HummingbirdCacheManagerCache <bool>(cacheManager, config.CacheRegion));
            });
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <object>), sp => {
                var cacheManager = sp.GetRequiredService <ICacheManager <object> >();
                return(new Hummingbird.Extensions.Cache.HummingbirdCacheManagerCache <object>(cacheManager, config.CacheRegion));
            });
            return(hostBuilder);
        }
 public static IHummingbirdHostBuilder AddStandardHttpClient(this IHummingbirdHostBuilder hostBuilder, HttpMessageHandler httpMessageHandler)
 {
     hostBuilder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
     hostBuilder.Services.AddSingleton <IHttpClientFactory, StandardHttpClientFactory>(sp =>
     {
         var logger = sp.GetRequiredService <ILogger <StandardHttpClient> >();
         var httpContextAccessor = sp.GetRequiredService <IHttpContextAccessor>();
         var serviceLocator      = sp.GetService <Hummingbird.DynamicRoute.IServiceLocator>();
         return(new StandardHttpClientFactory(logger, httpContextAccessor, serviceLocator));
     });
     hostBuilder.Services.AddSingleton <IHttpClient>(sp => sp.GetService <IHttpClientFactory>().CreateResilientHttpClient(httpMessageHandler));
     return(hostBuilder);
 }
Exemplo n.º 9
0
        /// <summary>
        /// 缓存实现幂等
        /// </summary>
        /// <param name="services"></param>
        public static IHummingbirdHostBuilder AddIdempotency(this IHummingbirdHostBuilder hostBuilder, Action <IIdempotencyOption> setupOption = null)
        {
            var option = new IdempotencyOption();

            if (setupOption != null)
            {
                setupOption(option);
            }

            hostBuilder.Services.AddSingleton <IIdempotencyOption>(option);
            hostBuilder.Services.AddSingleton <IRequestManager, CacheRequestManager>();
            return(hostBuilder);
        }
Exemplo n.º 10
0
        public static IHummingbirdHostBuilder AddUniqueIdGenerator(this IHummingbirdHostBuilder hostBuilder, Action <IdGeneratorOption> setup)
        {
            var option = new IdGeneratorOption();

            setup(option);

            hostBuilder.Services.AddSingleton <IUniqueIdGenerator>(sp =>
            {
                var workId = option.WorkIdCreateStrategy.NextId();
                return(new SnowflakeUniqueIdGenerator(workId, option.CenterId));
            });
            return(hostBuilder);
        }
Exemplo n.º 11
0
        public static IHummingbirdHostBuilder AddStandardHttpClient(this IHummingbirdHostBuilder hostBuilder)
        {
            hostBuilder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            hostBuilder.Services.AddSingleton <IHttpClientFactory, StandardHttpClientFactory>(sp =>
            {
                var Configuration       = sp.GetRequiredService <IConfiguration>();
                var logger              = sp.GetRequiredService <ILogger <StandardHttpClient> >();
                var httpContextAccessor = sp.GetRequiredService <IHttpContextAccessor>();


                return(new StandardHttpClientFactory(logger, httpContextAccessor));
            });
            hostBuilder.Services.AddSingleton <IHttpClient>(sp => sp.GetService <IHttpClientFactory>().CreateResilientHttpClient());
            return(hostBuilder);
        }
Exemplo n.º 12
0
        public static IHummingbirdHostBuilder AddEventBus(this IHummingbirdHostBuilder hostBuilder, Action <IHummingbirdEventBusHostBuilder> setup, Func <System.Reflection.Assembly[]> assemblies)
        {
            var types = assemblies()
                        .SelectMany(a => a.GetTypes().Where(type => Array.Exists(type.GetInterfaces(), t => t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(IEventHandler <>) || t.GetGenericTypeDefinition() == typeof(IEventBatchHandler <>)))))
                        .ToArray();

            foreach (var type in types)
            {
                hostBuilder.Services.AddSingleton(type);
            }

            var builder = new HummingbirdEventBusHostBuilder(hostBuilder.Services);

            setup(builder);

            return(hostBuilder);
        }
        public static IHummingbirdHostBuilder AddResilientHttpClient(this IHummingbirdHostBuilder hostBuilder, Action <string, ResilientHttpClientConfigOption> func = null, HttpMessageHandler httpMessageHandler = null)
        {
            hostBuilder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            hostBuilder.Services.AddSingleton <IHttpClientFactory, ResilientHttpClientFactory>(sp =>
            {
                var logger = sp.GetRequiredService <ILogger <ResilientHttpClient> >();
                var httpContextAccessor = sp.GetRequiredService <IHttpContextAccessor>();
                var serviceLocator      = sp.GetService <Hummingbird.DynamicRoute.IServiceLocator>();

                return(new ResilientHttpClientFactory(logger,
                                                      httpContextAccessor,
                                                      serviceLocator,
                                                      func));
            });
            hostBuilder.Services.AddSingleton <IHttpClient>(sp => sp.GetService <IHttpClientFactory>().CreateResilientHttpClient(httpMessageHandler));
            return(hostBuilder);
        }
Exemplo n.º 14
0
        public static IHummingbirdHostBuilder AddSnowflakeUniqueIdGenerator(
            this IHummingbirdHostBuilder hostBuilder,
            Action <IWorkIdCreateStrategyBuilder> workIdCreateStrategyBuilder)
        {
            var builder = new WorkIdCreateStrategyBuilder(hostBuilder.Services);

            workIdCreateStrategyBuilder(builder);

            hostBuilder.Services.AddSingleton <IUniqueIdGenerator>(sp =>
            {
                var WorkIdCreateStrategy = sp.GetService <IWorkIdCreateStrategy>();
                var workId = WorkIdCreateStrategy.NextId().Result;
                return(new SnowflakeUniqueIdGenerator(workId, builder.CenterId));
            });

#if NETCORE
            hostBuilder.Services.AddHostedService <InitWorkIdHostedService>();
#endif

            return(hostBuilder);
        }
Exemplo n.º 15
0
        public static IHummingbirdHostBuilder AddCache(this IHummingbirdHostBuilder hostBuilder, Action <IHummingbirdCacheConfig> setupOption = null)
        {
            var config = new HummingbirdCacheConfig();

            if (setupOption != null)
            {
                setupOption(config);
            }
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCacheConfig), config);
            hostBuilder.Services.AddSingleton(typeof(ICacheManager <object>), sp =>
            {
                var Configuration      = sp.GetRequiredService <IConfiguration>();
                var cacheConfiguration = Configuration.GetCacheConfiguration(config.ConfigName).Builder.Build();
                var cacheManager       = CacheFactory.FromConfiguration <object>(config.ConfigName, cacheConfiguration);



                return(cacheManager);
            });
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <object>), typeof(HummingbirdCacheManagerCache <object>));
            hostBuilder.Services.AddSingleton(typeof(IHummingbirdCache <>), typeof(HummingbirdCacheManagerCache <>));
            return(hostBuilder);
        }
Exemplo n.º 16
0
        /// <summary>
        /// 配置后台运行程序
        /// </summary>
        /// <param name="builder"></param>
        public static IHummingbirdHostBuilder AddQuartz(this IHummingbirdHostBuilder builder, IConfigurationSection configurationSection)
        {
            builder.Services.AddHostedService <CornJobSchedulerHostedService>();

            builder.Services.AddTransient <CornJobConfiguration>(sp =>
            {
                var logger = sp.GetService <ILogger <IConfiguration> >();
                var config = configurationSection.Get <CornJobConfiguration>();
                if (config == null)
                {
                    logger.LogWarning($"configuration section CornJob not found");
                    config = new CornJobConfiguration();
                }

                return(config);
            });

            builder.Services.AddQuartz(q => {
                // handy when part of cluster or you want to otherwise identify multiple schedulers
                q.SchedulerId = "Scheduler-Core";

                // we take this from appsettings.json, just show it's possible
                q.SchedulerName = "Quartz ASP.NET Core Scheduler";

                // as of 3.3.2 this also injects scoped services (like EF DbContext) without problems
                q.UseMicrosoftDependencyInjectionJobFactory();
                // or for scoped service support like EF Core DbContext
                //q.UseMicrosoftDependencyInjectionScopedJobFactory();

                // these are the defaults
                q.UseSimpleTypeLoader();
                q.UseInMemoryStore();
                q.UseDefaultThreadPool(tp =>
                {
                    tp.MaxConcurrency = 10;
                });

                // also add XML configuration and poll it for changes
                q.UseXmlSchedulingConfiguration(x =>
                {
                    x.Files                 = new[] { "~/quartz.config" };
                    x.ScanInterval          = TimeSpan.FromSeconds(2);
                    x.FailOnFileNotFound    = true;
                    x.FailOnSchedulingError = true;
                });

                // convert time zones using converter that can handle Windows/Linux differences
                q.UseTimeZoneConverter();

                // auto-interrupt long-running job
                q.UseJobAutoInterrupt(options =>
                {
                    // this is the default
                    options.DefaultMaxRunTime = TimeSpan.FromMinutes(60);
                });
            })
            .AddQuartzOpenTracing()
            .AddSingleton <Quartz.IScheduler>((sp) => {
                var scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;
                return(scheduler);
            });
            return(builder);
        }
Exemplo n.º 17
0
 public static IHummingbirdHostBuilder AddConsulDynamicRoute(this IHummingbirdHostBuilder hostBuilder, IConfiguration configuration, Action <ConsulConfigBuilder> setup = null)
 {
     hostBuilder.Services.AddConsulDynamicRoute(configuration, setup);
     return(hostBuilder);
 }
Exemplo n.º 18
0
 public static IHummingbirdHostBuilder AddConsulDynamicRoute(this IHummingbirdHostBuilder hostBuilder, IConfiguration configuration)
 {
     hostBuilder.Services.AddConsulDynamicRoute(configuration);
     return(hostBuilder);
 }
Exemplo n.º 19
0
        /// <summary>
        /// 添加微服务依赖
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IHummingbirdHostBuilder AddServiceRegistry(this IHummingbirdHostBuilder hostBuilder, Action <ServiceConfig> setupServiceConfig)
        {
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            _serviceConfig = _serviceConfig ?? new ServiceConfig();

            if (setupServiceConfig != null)
            {
                setupServiceConfig(_serviceConfig);
            }


            var policy = RetryPolicy.Handle <Exception>()
                         .Or <System.IO.IOException>()
                         .WaitAndRetryForever(a => { return(TimeSpan.FromSeconds(5)); }, (ex, time) =>
            {
                Console.WriteLine("WaitAndRetryForever" + ex.Message);
            });

            policy.Execute(() =>
            {
                var self_Register = _serviceConfig.SERVICE_SELF_REGISTER;
                _serviceConfig.SERVICE_REGISTRY_ADDRESS = _serviceConfig.SERVICE_REGISTRY_ADDRESS.Trim();

                if (self_Register == null || self_Register.ToLower() == bool.TrueString.ToString().ToLower())
                {
                    var client = new ConsulClient(obj =>
                    {
                        obj.Address    = new Uri($"http://{_serviceConfig.SERVICE_REGISTRY_ADDRESS}:{_serviceConfig.SERVICE_REGISTRY_PORT}");
                        obj.Datacenter = _serviceConfig.SERVICE_REGION;
                        obj.Token      = _serviceConfig.SERVICE_REGISTRY_TOKEN;
                    });

                    //计算健康检查地址
                    var SERVICE_80_CHECK_HTTP = _serviceConfig.SERVICE_80_CHECK_HTTP;

                    if (!SERVICE_80_CHECK_HTTP.Contains("http://"))
                    {
                        SERVICE_80_CHECK_HTTP = $"http://{_serviceConfig.SERVICE_ADDRESS}:{_serviceConfig.SERVICE_PORT}/{SERVICE_80_CHECK_HTTP.TrimStart('/')}";
                    }

                    var result = client.Agent.ServiceRegister(new AgentServiceRegistration()
                    {
                        ID                = _serviceConfig.SERVICE_ID,
                        Name              = _serviceConfig.SERVICE_NAME,
                        Address           = _serviceConfig.SERVICE_ADDRESS,
                        Port              = int.Parse(_serviceConfig.SERVICE_PORT),
                        Tags              = new[] { _serviceConfig.SERVICE_TAGS },
                        EnableTagOverride = true,
                        Check             = new AgentServiceCheck()
                        {
                            Status   = HealthStatus.Passing,
                            HTTP     = SERVICE_80_CHECK_HTTP,
                            Interval = TimeSpan.FromSeconds(int.Parse(_serviceConfig.SERVICE_80_CHECK_INTERVAL.TrimEnd('s'))),                           //5秒执行一次健康检查
                            Timeout  = TimeSpan.FromSeconds(int.Parse(_serviceConfig.SERVICE_80_CHECK_TIMEOUT.TrimEnd('s'))),                            //超时时间3秒
                            //TTL = TimeSpan.FromSeconds(int.Parse(_serviceConfig.SERVICE_80_CHECK_INTERVAL.TrimEnd('s')) * 3),//生存周期3个心跳包
                            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(int.Parse(_serviceConfig.SERVICE_80_CHECK_INTERVAL.TrimEnd('s')) * 3), //2个心跳包结束
                        }
                    }).Result;

                    Console.WriteLine($"ServiceRegister({_serviceConfig.SERVICE_ID}");
                }
            });

            return(hostBuilder);
        }