OsharpNS轻量级.net core快速开发框架简明入门教程-Osharp.Hangfire使用

OsharpNS轻量级.net core快速开发框架简明入门教程

教程目录

  1. 从零开始启动Osharp

    1.1. 使用OsharpNS项目模板创建项目

    1.2. 配置数据库连接串并启动项目

    1.3. OsharpNS.Swagger使用实例(登录和授权)

    1.4. Angular6的前端项目启动

  2. Osharp代码生成器的使用

    2.1 生成器的使用

    2.2 生成代码详解(如何自己实现业务功能)

  3. Osharp部分模块使用

    3.1 Osharp.Redis使用

    3.2 Osharp.Hangfire使用

    3.3 Osharp.Permissions使用

  4. Osharp深度学习和使用

    4.1 切换数据库(从SqlServer改为MySql)

    4.2 多上下文配置(多个数据库的使用)

    4.3. 自定义模块的定义(Senparc.Weixin的使用)

    4.4. 继续学习中....

OsharpNS官方资源
项目地址:https://github.com/i66soft/osharp-ns20
演示地址:https://www.osharp.org 直接使用QQ登录可以查看效果
文档地址:https://docs.osharp.org 正在完善中....
发布博客:https://www.cnblogs.com/guomingfeng/p/osharpns-publish.html 大神看这个文档应该就能跑起来,从零开始启动Osharp基于此文档完成
VS生成器插件:https://marketplace.visualstudio.com/items?itemName=LiuliuSoft.osharp
官方交流QQ群:85895249

OsharpNS.Hangfire使用

  1. 启用OsharpNS.Hangfire

    配置文件中找到配置节点Hangfire (配置文件有两个,一个开发,一个发布,别改错地方)

        "Hangfire": {
          "WorkerCount": 20,
          "StorageConnectionString": "Server=phone.qiadoo.com;Port=3306;UserId=candoo;Password=密码;Database=CanDoo.KaKa.Hangfire;charset='utf8';Allow User Variables=True", //这里是数据库的连接串 用什么数据库就用什么数据库的连接串(官方默认是SqlServer的,我这里用的是MySql)
    
          "DashboardUrl": "/hangfire",
          "Roles": "", //这个有可能确定可以访问的用户的角色,没测试过
    
          "Enabled": true
    
        }
  2. 改用MySql作为Hangfire的数据库

    官方使用的是SqlServer,只要配置好连接串就可以使用了,我用的是MySql,所以要改动一些东西

    2.1 安装Hangfire的MySql支持库

      通过Nuget安装`Hangfire.MySql.Core`

    2.2 Startups中继承HangfirePack新建一个MyHangfirePack

    
    using Hangfire;
    using Hangfire.MySql.Core;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using OSharp.Extensions;
    using OSharp.Hangfire;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace CanDoo.Test.Web.Startups
    {
        public class MyHangfirePack : HangfirePack
        {
            /// <summary>
            /// AddHangfire委托,重写可配置Hangfire服务,比如使用UseSqlServerStorage等
            /// </summary>
            /// <param name="services">服务容器</param>
            /// <returns></returns>
            protected override Action<IGlobalConfiguration> GetHangfireAction(IServiceCollection services)
            {
                IConfiguration configuration = services.GetConfiguration();
                string storageConnectionString = configuration["OSharp:Hangfire:StorageConnectionString"].CastTo<string>();
                if (storageConnectionString != null)
                {
                    return config => config.UseStorage(new MySqlStorage(storageConnectionString));
                }
    
                return config => { };
            }
        }
    }
  3. 看看效果

    3.1 按照连接串去新建Hangfire用的空数据库(只要库就可以,表自己会生成)

    3.2 启动web项目

    3.3 访问http://localhost:7001/hangfire/就能看到Hangfire的界面了

    3.4 具体的使用参考,文件位于CanDoo.Test.Web.Hangfire

   // -----------------------------------------------------------------------
   //  <copyright file="HangfireJobRunner.cs" company="OSharp开源团队">
   //      Copyright (c) 2014-2018 OSharp. All rights reserved.
   //  </copyright>
   //  <site>http://www.osharp.org</site>
   //  <last-editor>郭明锋</last-editor>
   //  <last-date>2018-12-31 17:36</last-date>
   // -----------------------------------------------------------------------
   
   using System;
   using System.Collections.Generic;
   using System.Diagnostics;
   using System.Linq;
   using System.Threading.Tasks;
   
   using Hangfire;
   
   using CanDoo.Test.Identity;
   using CanDoo.Test.Identity.Entities;
   
   using Microsoft.AspNetCore.Identity;
   using Microsoft.Extensions.DependencyInjection;
   
   using OSharp.Collections;
   using OSharp.Dependency;
   using OSharp.Entity;
   using OSharp.Hangfire;

   namespace CanDoo.Test.Web.Hangfire
   {
       [Dependency(ServiceLifetime.Singleton)]
       public class HangfireJobRunner : IHangfireJobRunner
       {
           public void Start()
           {
               BackgroundJob.Enqueue<UserManager<User>>(m => m.FindByIdAsync("1"));
               string jobId = BackgroundJob.Schedule<UserManager<User>>(m => m.FindByIdAsync("2"), TimeSpan.FromMinutes(2));
               BackgroundJob.ContinueWith<TestHangfireJob>(jobId, m => m.GetUserCount());
               RecurringJob.AddOrUpdate<TestHangfireJob>(m => m.GetUserCount(), Cron.Minutely, TimeZoneInfo.Local);
               RecurringJob.AddOrUpdate<TestHangfireJob>(m=>m.LockUser2(), Cron.Minutely, TimeZoneInfo.Local);
           }
       }

       public class TestHangfireJob
       {
           private readonly IIdentityContract _identityContract;
           private readonly IServiceProvider _provider;
    
           /// <summary>
           /// 初始化一个<see cref="TestHangfireJob"/>类型的新实例
           /// </summary>
           public TestHangfireJob(IIdentityContract identityContract, IServiceProvider provider)
           {
               _identityContract = identityContract;
               _provider = provider;
           }
    
           /// <summary>
           /// 获取用户数量
           /// </summary>
           public string GetUserCount()
           {
               List<string> list = new List<string>();
               list.Add(_identityContract.Users.Count().ToString());
               list.Add(_identityContract.GetHashCode().ToString());
               return list.ExpandAndToString();
           }
    
           public async Task<string> LockUser2()
           {
               List<string> list = new List<string>();
               UserManager<User> userManager = _provider.GetService<UserManager<User>>();
               User user2 = await userManager.FindByIdAsync("2");
               list.Add($"user2.IsLocked: {user2.IsLocked}");
               user2.IsLocked = !user2.IsLocked;
               await userManager.UpdateAsync(user2);
               IUnitOfWork unitOfWork = _provider.GetUnitOfWork<User, int>();
               unitOfWork.Commit();
               user2 = await userManager.FindByIdAsync("2");
               list.Add($"user2.IsLocked: {user2.IsLocked}");
               return list.ExpandAndToString();
           }
       }

   }

转载于:https://www.cnblogs.com/candoo/p/10795095.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我理解了你的问题。关于 Hangfire、MySQL 和 ASP.NET Core 3.1 的使用,我可以给出一些异常解决的建议。 首先,确保你已经按照官方文档正确地安装和配置了 Hangfire 和 MySQL。然后,根据你遇到的异常,尝试以下解决方法: 1. "Could not load file or assembly 'MySql.Data' or one of its dependencies" 异常 这个异常通常是由于缺少 MySQL 数据库驱动程序引起的。你需要在项目中添加对 MySQL 数据库驱动程序的引用。可以通过 NuGet 包管理器来安装 MySQL.Data。 2. "Specified key was too long; max key length is 767 bytes" 异常 这个异常是由于 MySQL 的索引长度限制引起的。解决方法是,在你的 DbContext 类中覆盖 OnModelCreating 方法,将所有字符串属性的最大长度设置为 255。 ``` protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var property in modelBuilder.Model.GetEntityTypes() .SelectMany(t => t.GetProperties()) .Where(p => p.ClrType == typeof(string))) { property.SetMaxLength(255); } } ``` 3. "MySqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding" 异常 这个异常通常是由于 MySQL 连接超时引起的。解决方法是,在连接字符串中添加 Connection Timeout 参数,例如: ``` "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;Connection Timeout=60;" ``` 这将使连接超时时间为 60 秒。 希望这些解决方法能帮助你解决异常问题。如果你还有其他问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值