C#通過IronPython內嵌Python腳本,實現了對業務邏輯抽象及判斷,適合在大量訂單需要進行校驗的場合使用。
比如,貸款時會對用戶進行核查,核查過程可能存在多個節點,並且節點可能會隨着政策而不斷改變,每個節點就相當於一個腳本,通過腳本的出口關鍵字來確定流程分支走向。
大概業務流程圖如下:

代碼實現部分
1、C#代碼
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace IronPython調用示例
{
class Program
{
static void Main(string[] args)
{
string logPath = Path.Combine("logs", "log.txt");
if (File.Exists(logPath))
{
File.Delete(logPath);
}
FileStream fileStream = new FileStream(logPath, FileMode.OpenOrCreate);
//Console.WriteLine("------------------------以下是C#執行日志信息------------------------");
try
{
string pythonCodePath = Path.Combine("templates", "pythonCode.txt");
string sourceCodePath = Path.Combine("pys", "performer.py");
if (!File.Exists(pythonCodePath))
{
throw new Exception("Python模板不存在!");
}
if (!File.Exists(sourceCodePath))
{
throw new Exception("Python源代碼文件不存在!");
}
string[] pythonCodeContent = File.ReadAllText(pythonCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
string[] sourceCodeContent = File.ReadAllText(sourceCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
if (sourceCodeContent == null || sourceCodeContent.Length == 0)
{
throw new Exception("Python代碼不能為空!");
}
List<string> strList = new List<string>(pythonCodeContent);
foreach (var item in sourceCodeContent)
{
strList.Add(" " + item);
}
string codes = "";
foreach (var s in strList)
{
codes += s + Environment.NewLine;
}
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromString(codes);
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
dynamic performer = scope.GetVariable("performer");
dynamic per = performer("1005");
per.run();
var out_param = per.out_param;
Console.WriteLine(per.out_param);
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
finally
{
fileStream.Close();
fileStream.Dispose();
}
}
}
}
2、Python代碼,模板(pythonCode.txt)
#.coding=utf-8
import db_manager
class performer():
def __init__(self,in_param):
self.out_param = ''
self.in_param = in_param
def run(self):
3、節點腳本(performer.py)
import datetime
def get_now_time():
self.out_param = str(datetime.datetime.now())
def get_user_count():
order_id = self.in_param
sql = "select * from user_info where id = "+ order_id +""
querys = db_manager.sqlserver().execute_query(sql)
if(len(querys) >= 5):
self.out_param = '業務辦理失敗,此用戶在全國范圍內辦理號碼已經超過了5個!'
else:
self.out_param = '初審通過,已進入人工審核階段!'
get_now_time()
get_user_count()
注意,此項目需要安裝IronPython,並且把里面bin目錄復制到我們C# debug目錄下,項目源代碼:https://github.com/lishuyiba/PythonPerformer
