我有一个返回服务总线消息的 azure 函数。但是,我想有条件地返回一条服务总线消息,而不是每次都被强制返回消息。
这里有一个例子
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string ServiceBusOutput([HttpTrigger] dynamic input, ILogger log)
{
log.LogInformation($"C# function processed: {input.Text}");
// check condition here, abort return completely
// Otherwise, return
return input.Text;
}
换句话说,我想在函数代码块中应用某些条件时在服务总线上返回一条消息。这可能吗?
一个行不通的想法是抛出异常。但是,这只会导致消息被放入 DL 队列中。我想完全中止服务总线上返回消息的操作,避免DL。
另一个行不通的想法是简单地执行
return;
但这会导致编译时错误,这是意料之中的 “需要一个类型可转换为‘MyReturnType1’的对象”
我能想到一个我不喜欢的 hack,即返回 null,然后在链的后面处理 null。但这对我来说有点脏。
您可以将
ServiceBus
绑定为MessageSender
类型,然后使用SendAsync()
方法发送消息。
下面是我的测试代码,如果请求名称等于“george”,它会将名称发送到消息队列。
public static class Function1
{
[FunctionName("Function1")]
public static async System.Threading.Tasks.Task RunAsync(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[ServiceBus("myqueue", Connection = "ServiceBusConnection")] MessageSender messagesQueue,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
if (name.Equals("george")) {
byte[] bytes = Encoding.ASCII.GetBytes(name);
Message m1 = new Message();
m1.Body = bytes;
await messagesQueue.SendAsync(m1);
}
}
}
假设这就是你想要的,希望这对你有帮助,如果你还有其他问题,请随时告诉我。
您可以从函数内部创建的自定义队列客户端向队列发送消息,而不是使用 Azure 函数中可用的输出绑定。
绑定无法根据条件发布消息。
只需从函数返回 null,它不会发送消息。