예제 #1
0
        public static void Main(string[] args)
        {
            // Bootstrap and start the OWIN host
            string baseUri = "http://localhost:5000";

            Args = args;
            WebApp.Start <Startup>(baseUri);
            Logger logger = ApplicationLog.CreateLogger <Program>();

            logger.Info($"Server running at {baseUri} - press Enter to quit. ");
            Console.ReadLine();
        }
예제 #2
0
        public void Configuration(IAppBuilder app)
        {
            // Setup logging
            ApplicationLog.AddConsole();
            Logger logger = ApplicationLog.CreateLogger <Startup>();

            logger.Info("Initializing service");

            // Build an IConfiguration instance using the ConfigurationBuilder as normal
            Dictionary <string, string> collection = new Dictionary <string, string>()
            {
                { "key1", "value1" }, { "key2", "value2" }
            };
            var config1 = new ConfigurationBuilder().AddInMemoryCollection(collection).Build();
            var config3 = new ConfigurationBuilder().AddJsonFile("Config.json").Build();

            // AppConfig is a static class that groups together instances of IConfiguration and makes them available statically anywhere in the application
            AppConfig.AddConfigurationObject(config1, "memorySource");
            AppConfig.AddConfigurationObject(config3, "jsonSource");

            // The above configuration sources can now be referenced easily with a static helper function
            Console.WriteLine("key1 key in memorySource: " + AppConfig.Get("memorySource", "key1"));
            Console.WriteLine("config:setting key in jsonSource: " + AppConfig.Get("jsonSource", "config:setting"));

            // Runtime configuration can be updated easily as well
            AppConfig.Set("jsonSource", "config:setting", "http://localhost:5001");
            Console.WriteLine("Modified config:setting key in jsonSource: " + AppConfig.Get("jsonSource", "config:setting"));

            // Redis health check (Requires StackExchange.Redis)
            //HealthCheckRegistry.RegisterHealthCheck("Redis", () => RedisHealthCheck.CheckHealth("localhost"));
            // PostgreSQL health check (Requires Npgsql)
            //HealthCheckRegistry.RegisterHealthCheck("Postgresql", () => PostgresqlHealthCheck.CheckHealth("Host=localhost;Username=postgres;Password=postgres;Database=postgres"));
            // SQL Server health check (Requires System.Data.SqlClient)
            //HealthCheckRegistry.RegisterHealthCheck("SqlServer", () => SqlServerCheck.CheckHealth("Server=localhost;Database=master;User Id=sa;Password=password; "));
            // HealthCheckRegistry.RegisterHealthCheck("mongodb", () => MongoHealthCheck.CheckHealth("mongodb://localhost:27017"));

            /*
             *   Health checks are simply functions that return either healthy or unhealthy with an optional message string
             */
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor", () => HealthResponse.Healthy("Test Message"));
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor2", () => HealthResponse.Healthy("Test Message2"));
            HealthCheckRegistry.RegisterHealthCheck("SampleOperation", () => SampleHealthCheckOperation());

            // Activate the info endpoint
            app.UseInfoEndpoint();

            // Activate the environment endpoint
            app.UseEnvironmentEndpoint();

            // Activate the health endpoint
            app.UseHealthEndpoint();
        }
예제 #3
0
        public void Configure(IApplicationBuilder app)
        {
            // Add logging
            ApplicationLog.AddConsole();
            ApplicationLog.AddFile("Test.log");
            Logger logger = ApplicationLog.CreateLogger <Startup>();

            logger.Info("Initializing service");

            // Build an IConfiguration instance using the ConfigurationBuilder as normal
            Dictionary <string, string> collection = new Dictionary <string, string>()
            {
                { "key1", "value1" }, { "key2", "value2" }
            };
            var config1 = new ConfigurationBuilder().AddInMemoryCollection(collection).Build();
            var config2 = new ConfigurationBuilder().SetBasePath(_env.ContentRootPath).AddIniFile("hosting.ini").Build();
            var config3 = new ConfigurationBuilder().SetBasePath(_env.ContentRootPath).AddJsonFile("config.json").Build();

            // AppConfig is a static class that groups together instances of IConfiguration and makes them available statically anywhere in the application
            AppConfig.AddConfigurationObject(config1, "memorySource");
            AppConfig.AddConfigurationObject(config2, "iniSource");
            AppConfig.AddConfigurationObject(config3, "jsonSource");

            // The above configuration sources can now be referenced easily with a static helper function
            Console.WriteLine("key1 key in memorySource: " + AppConfig.Get("memorySource", "key1"));
            Console.WriteLine("server.urls key in iniSource: " + AppConfig.Get("iniSource", "server.urls"));

            // Runtime configuration can be updated easily as well
            AppConfig.Set("iniSource", "server.urls", "http://localhost:5001");
            Console.WriteLine("Modified server.urls key in iniSource: " + AppConfig.Get("iniSource", "server.urls"));

            /*
             *   Health checks are simply functions that return either healthy or unhealthy with an optional message string
             */
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor", () => HealthResponse.Healthy("Test Message"));
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor2", () => HealthResponse.Healthy("Test Message2"));
            HealthCheckRegistry.RegisterHealthCheck("SampleOperation", () => SampleHealthCheckOperation());

            /*
             *   Some bundled health checks that can be used
             */
            // Redis health check (Requires StackExchange.Redis)
            //HealthCheckRegistry.RegisterHealthCheck("Redis", () => RedisHealthCheck.CheckHealth("localhost"));
            // PostgreSQL health check (Requires Npgsql)
            //HealthCheckRegistry.RegisterHealthCheck("Postgresql", () => PostgresqlHealthCheck.CheckHealth("Host=localhost;Username=postgres;Password=postgres;Database=postgres"));
            // SQL Server health check (Requires System.Data.SqlClient)
            //HealthCheckRegistry.RegisterHealthCheck("SqlServer", () => SqlServerCheck.CheckHealth("Server=localhost;Database=master;User Id=sa;Password=password; "));
            // RavenDB health check
            //HealthCheckRegistry.RegisterHealthCheck("ravendb", () => RavenDbHealthCheck.CheckHealth("Url=http://192.168.153.55:8080;DefaultDatabase=<system>"));
            // MongoDB health check
            //HealthCheckRegistry.RegisterHealthCheck("mongodb", () => MongoHealthCheck.CheckHealth("mongodb://localhost:27017"));

            /*
             *  Uncomment the below line to only allow access to the actuator endpoints from localhost
             *
             *  Allowed patterns are:
             *
             *  1. CIDR range: "192.168.0.0/24", "fe80::/10"
             *  2. Single address: "127.0.0.1", ":;1"
             *  3. Begin end range: "169.258.0.0-169.258.0.255"
             *  4. Bit mask range: "192.168.0.0/255.255.255.0"
             *
             *  NOTE: Currently this feature is not supported under Kestrel self-host as it does not set the client's IP address in HttpContext
             */

            //MicroserviceBootstrap.AllowedIpAddresses = IpAddressRange.Parse("127.0.0.0/8");

            // Activate /health endpoint
            app.UseHealthEndpoint();

            /*
             * Activate /env endpoint
             *
             * The ApplicationConfiguration element of the env endpoint will only contain data if the AppConfig helper class is
             * used to manage application configuration
             */
            app.UseEnvironmentEndpoint();

            /*
             *   The compiler directive below is only required if you plan to target .NET core as well as the full CLR
             *   If you don't target dnxcore50 in your project.json you can remove the below #if and just call UseInfoEndpoint()
             *   without any parameters
             */

            // Activate /info endpoint
#if NETCOREAPP1_0
            // Required for .NET Core until the relevant APIs are added
            app.UseInfoEndpoint(typeof(Startup).GetTypeInfo().Assembly.GetName());
#else
            app.UseInfoEndpoint();
#endif
        }
예제 #4
0
        /// <summary>
        /// Scheduler在JobDetail被执行之后调用这个方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default)
        {
            try
            {
                lock (_lock)
                {
                    var trigger   = (CronTriggerImpl)((JobExecutionContextImpl)context).Trigger;
                    var result    = context.Scheduler.Context.Get(trigger.FullName + "_Result");    /*返回结果*/
                    var exception = context.Scheduler.Context.Get(trigger.FullName + "_Exception"); /*异常信息*/
                    var time      = context.Scheduler.Context.Get(trigger.FullName + "_Time");      /* 耗时*/

                    var jobinfo_repository = IocEx.Instance.GetService <IJobInfoRepository>();

                    var job = jobinfo_repository.Get(x => x.JobName.Equals(trigger.Name) && x.JobGroup.Equals(trigger.JobGroup) && x.IsDelete == 0);

                    if (job == null)
                    {
                        job = new JobInfo
                        {
                            Id         = Guid.NewGuid().ToString(),
                            JobName    = trigger.JobName,
                            JobGroup   = trigger.JobGroup,
                            JobValue   = context.JobDetail.JobDataMap.ToJson(),
                            IsDelete   = 0,
                            JobCount   = 1,
                            JobClass   = context.JobDetail.JobType.FullName,
                            JobStatus  = (int)TriggerState.Normal,
                            JobResult  = result.ToJson(),
                            JobCron    = trigger.CronExpressionString,
                            CreateTime = DateTime.Now,
                            JobRunTime = time != null?Convert.ToInt32(time) : 0,
                                             JobStartTime = trigger.StartTimeUtc.LocalDateTime,
                                             JobNextTime  = trigger.GetNextFireTimeUtc().GetValueOrDefault().LocalDateTime
                        };
                        jobinfo_repository.Add(job, true);
                    }
                    else
                    {
                        job.JobStartTime = trigger.StartTimeUtc.LocalDateTime;
                        job.JobValue     = context.JobDetail.JobDataMap.ToJson();
                        job.JobCron      = trigger.CronExpressionString;
                        job.JobCount    += 1;
                        job.JobRunTime   = time != null?Convert.ToInt32(time) : 0;

                        job.JobNextTime = trigger.GetNextFireTimeUtc().GetValueOrDefault().LocalDateTime;
                        job.UpdateTime  = DateTime.Now;
                        job.JobResult   = result.ToJson();
                        jobinfo_repository.Update(job, true);
                    }

                    //记录错误
                    if (exception != null)
                    {
                        var joberror_repository = IocEx.Instance.GetService <IJobErrorRepository>();
                        var error = new JobError
                        {
                            Id         = Guid.NewGuid().ToString(),
                            JobId      = job.Id,
                            JobCount   = job.JobCount,
                            IsDelete   = 0,
                            CreateTime = DateTime.Now,
                            Message    = exception.ToJson()
                        };

                        joberror_repository.Add(error, true);
                    }

                    ApplicationLog.CreateLogger <JobListener>().LogInformation($"任务监听:{job.ToJson()}");
                    return(Task.CompletedTask);
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.CreateLogger <JobListener>().LogError(new EventId(ex.HResult), ex, "---JobWasExecuted Exception---");
                return(Task.CompletedTask);
            }
        }