网站首页 网站源码
using System;
using System.Threading.Tasks;
using Dpz.Core.WebApi.Models;
using Hangfire;
using LibGit2Sharp;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Dpz.Core.WebApi.Hangfire;
/// <summary>
/// 更新代码任务调度
/// </summary>
public class UpdateCodeActivator : JobActivator
{
private readonly IConfiguration _configuration;
private readonly ILogger<UpdateCodeActivator> _logger;
/// <summary>
/// ctor
/// </summary>
public UpdateCodeActivator(IConfiguration configuration, ILogger<UpdateCodeActivator> logger)
{
_configuration = configuration;
_logger = logger;
}
/// <summary>
/// 更新代码
/// </summary>
[ProlongExpirationTime(ExpirationTimeoutDays = 90)]
public async Task UpdateAsync()
{
var codeView = _configuration.GetSection("CodeView").Get<CodeViewOption>();
var githubToken = _configuration.GetSection("GithubToken").Get<string>();
await Task.Factory.StartNew(() =>
{
try
{
using var repository = new Repository(codeView.SourceCodeRoot);
var options = new PullOptions
{
FetchOptions = new FetchOptions
{
CredentialsProvider = (_, _, _) =>
new UsernamePasswordCredentials()
{
Username = "pengqian089",
Password = githubToken
},
CertificateCheck = (_, _, _) => true
}
};
var signature = new Signature(
new Identity("WebApi", "pengqian089@gmail.com"), DateTimeOffset.Now);
Commands.Pull(repository, signature, options);
}
catch (Exception e)
{
_logger.LogError(e, "fetch fail");
}
});
}
}
上述代码是一个使用 Hangfire 进行任务调度的 C# 类,名为 UpdateCodeActivator
。它的主要功能是从 GitHub 仓库中更新代码。以下是代码的详细解释:
UpdateCodeActivator
继承自 JobActivator
,这是 Hangfire 中用于创建作业的类。IConfiguration
和 ILogger<UpdateCodeActivator>
。IConfiguration
用于读取配置文件中的设置,ILogger
用于记录日志。UpdateAsync
方法签名: public async Task UpdateAsync()
是一个异步方法,用于更新代码。
配置读取:
CodeView
和 GithubToken
。CodeView
是一个自定义的配置类,包含源代码的根目录。任务执行:
Task.Factory.StartNew
启动一个新的任务来执行代码更新操作。try
块中,使用 LibGit2Sharp
库来处理 Git 操作。Git 操作:
Repository
实例,指向源代码的根目录。PullOptions
,包括:FetchOptions
:配置 Git 凭据提供者,使用 GitHub 的用户名和令牌进行身份验证。CertificateCheck
:设置为始终返回 true
,表示忽略 SSL 证书检查(在生产环境中不推荐这样做)。Signature
对象,包含提交者的身份信息(用户名和邮箱)。Commands.Pull
方法从远程仓库拉取最新的代码。异常处理:
_logger
记录错误信息。[ProlongExpirationTime(ExpirationTimeoutDays = 90)]
: 这是一个 Hangfire 特性,表示该作业的过期时间被延长至 90 天。这意味着即使作业在 90 天内没有被执行,它仍然会保持在 Hangfire 的作业队列中。整体而言,UpdateCodeActivator
类的功能是定期从 GitHub 仓库中拉取最新的代码,并在出现错误时记录日志。它利用了 Hangfire 进行任务调度,使用 LibGit2Sharp
进行 Git 操作,并通过配置文件管理敏感信息(如 GitHub 令牌)。