Zeebe .Net Core 客户端(八)用C#编写Zeebe控制台

Zeebe带有控制台程序,但使用起来有些复杂,我们现在使用c#编写一个简单的Zeebe控制台程序,完成流程导入,实例创建,消息发送等功能。首先,在Visual Studio中创建一个.Net Core的控制台项目,然后使用NuGet程序包管理器引入zb-client,下面是程序代码:

using NLog.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Zeebe.Client;

namespace ZeebeConsole
{
    class Program
    {
        private static readonly string ZeebeUrl = "127.0.0.1:26500";
        static async Task Main(string[] args)
        {
            var client = ZeebeClient.Builder()
                 .UseLoggerFactory(new NLogLoggerFactory())
                 .UseGatewayAddress(ZeebeUrl)
                 .UsePlainText()
                 .Build();

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("欢迎使用流程引擎测试命令行工具\r\n");
            Console.ResetColor();
            while (true)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write(">");
                var command = Console.ReadLine();
                Console.ResetColor();
                if (command.ToLower() == "exit")
                {
                    Console.WriteLine("结束运行");
                    return;
                }
                var res = await ProcessCommand(client,command);
                if (!string.IsNullOrEmpty(res)) Console.WriteLine(res);
            }
        }

        private static async Task<string> ProcessCommand(IZeebeClient client, string command)
        {
            try
            {
                var arr = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (arr.Count() > 0)
                {
                    var commandname = arr[0].ToLower();

                    switch (commandname)
                    {
                        case "info":
                            return await Utility.InfoAsync(client);
                        case "import":
                            if (arr.Count() < 2)
                            {
                                return "缺少流程文件路径";
                            }
                            return await Utility.ImportFlowDefineAsync(client,arr[1]);
                        case "create":
                            if (arr.Count() < 3)
                            {
                                return "缺少流程名称和初始参数(参数1=值1;参数2=值2)";
                            }
                            return await Utility.CreateAndStartAsync(client, arr[1],arr[2]);
                        case "remove":
                            if (arr.Count() < 2)
                            {
                                return "缺少流程key";
                            }
                            return await Utility.RemoveInstanceAsync(client, arr[1]);
                        case "message":
                            if (arr.Count() < 4) return "缺少参数,message messagename relatekey 参数(参数1=值1;参数2=值2)";
                           return await Utility.SendMessageAsync(client,arr[1], arr[2], arr[3]);
                    }
                }
                if (!string.IsNullOrEmpty(command)) return "无法识别的命令:" + command;
            }
            catch (Exception ex)
            {
                return "发生错误:" + ex.Message;
            }

            return "";
        }
    }
}

using System;
using Zeebe.Client;

namespace ZeebeConsole
{
    internal class Utility
    {
        internal static async System.Threading.Tasks.Task<string> ImportFlowDefineAsync(IZeebeClient client, string processPath)
        {
            var deployResponse = await client.NewDeployCommand()
                 .AddResourceFile(processPath)
                 .Send();
            var res = deployResponse.Workflows[0].BpmnProcessId + "\r\n" + deployResponse.Workflows[0].Version + "\r\n" + deployResponse.Workflows[0].WorkflowKey;
            return res;
        }

        internal static async  System.Threading.Tasks.Task<string> InfoAsync(IZeebeClient client)
        {
            var topology = await client.TopologyRequest()
                .Send();
            return topology.ToString();
        }

        internal static async System.Threading.Tasks.Task<string> CreateAndStartAsync(IZeebeClient client, string flowname, string paras)
        {
            var WorkflowInstanceVariables = getJson(paras);

            var workflowInstance = await client
             .NewCreateWorkflowInstanceCommand()
             .BpmnProcessId(flowname)
             .LatestVersion()
             .Variables(WorkflowInstanceVariables)
             .Send();
            return workflowInstance.WorkflowInstanceKey.ToString();
        }
               

        internal static async System.Threading.Tasks.Task<string> RemoveInstanceAsync(IZeebeClient client, string key)
        {
            await client.NewCancelInstanceCommand(long.Parse(key)).Send();
            return "removed";
        }

        internal static async System.Threading.Tasks.Task<string> SendMessageAsync(IZeebeClient client, string messageName, string key, string paras)
        {
            if (key == "none") key = string.Empty;
            var WorkflowInstanceVariables = getJson(paras);
            var resp = await client.NewPublishMessageCommand()
                    .MessageName(messageName)
                    .CorrelationKey(key)
                    .Variables(WorkflowInstanceVariables)
                    .Send();
            return "Message Sent";
        }

        private static string getJson(string paras)
        {
            if (!string.IsNullOrEmpty(paras)) 
            {
                var json = "";
                var arrparas = paras.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                foreach (var p in arrparas)
                {
                    var vals = p.Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (vals.Length == 2)
                    {
                        json += "\"" + vals[0] + "\":" + vals[1].Replace("'", "\"")+",";
                    }
                }
                json=json.Trim(',');
                return "{" + json + "}";
            }

            return "{}";
        }
    }
}

这个控制台程序有如下几个命令:

  • info : 显示基本信息
  • import : 导入流程文件
  • create : 创建流程实例
  • remove : 删除流程实例
  • message : 发送消息
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。