Dapr .NetCore 绑定输入输出 电脑版发表于:2021/12/22 10:31 ![](https://img.tnblog.net/arcimg/hb/896fd38e95b346f9a0d98c54b135bb94.jpg) >#Dapr .NetCore 绑定输入输出 [TOC] 输入绑定 ------------ tn2>简单来说通过你的应用所对应的dapr边车绑定队列的消息处理,但是这个消息中间件可以自定义。 比如我们接下来的案例大致如下: ![](https://img.tnblog.net/arcimg/hb/cde85f1964bb4c10b50a75391584a230.png) tn>这里没用Redis的原因是因为它不支持,关于中间价支持的列表参考如下: https://docs.dapr.io/reference/components-reference/supported-bindings/ >###Demo tn2>首先我们需要创建Rabbitmq中间件,可以参考我的这两篇文章 https://www.tnblog.net/hb/article/details/6627 https://www.tnblog.net/hb/article/details/5179 ![](https://img.tnblog.net/arcimg/hb/42856d069af140e19abfdc754baddda5.png) tn2>随后我们创建一个.netcore的webapi,并添加相关依赖 ```csharp <PackageReference Include="Dapr.AspNetCore" Version="1.4.0" /> ``` tn2>添加相关服务 ```csharp services.AddControllers().AddDapr(); ``` tn2>定义控制器(`MyRabbitmq`) ```csharp [Route("MyRabbitmq")] [ApiController] public class MyRabbitmqController:Controller { ILogger<MyRabbitmqController> _log; public MyRabbitmqController( ILogger<MyRabbitmqController> log ){ _log = log; } [HttpPost("InputCheck")] public void InputRegisterBind() { Stream stream = Request.Body; byte[] buffer = new byte[Request.ContentLength.Value]; stream.ReadAsync(buffer, 0, buffer.Length); string content = Encoding.UTF8.GetString(buffer); _log.LogInformation(".............binding............." + content); } } ``` tn2>接着我们需要在我们的`~/.dapr/components`下定义我们Rabbitmq(`rabbitmqbind.yaml`)的组件,请参考如下示例: ```yaml apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: myrabbitmq spec: type: bindings.rabbitmq version: v1 metadata: - name: queueName value: queue1 - name: host value: amqp://guest:guest@192.168.43.166:5672 - name: durable value: true - name: deleteWhenUnused value: false - name: ttlInSeconds value: 60 - name: prefetchCount value: 0 - name: exclusive value: false - name: maxPriority value: 5 - name: contentType value: "text/plain" - name: route value: /MyRabbitmq/InputCheck ``` tn2>关于定义中route是定义我们的rabbitmq消息在该应用中在哪儿进行处理。其他参数请参考: https://docs.dapr.io/reference/components-reference/supported-bindings/ 最后执行如下命令运行我们的app ```bash dapr run --app-id myapp --app-port 5000 --dapr-http-port 3500 -- dotnet run ``` tn2>最后我们在rabbitmq中找到我们定义的queue1队列,并在里面进行发布消息,可以看到它已经在我们的程序中进行了消息处理。 ![](https://img.tnblog.net/arcimg/hb/46d206fc7cbc499f927f9e215c403777.png) ![](https://img.tnblog.net/arcimg/hb/a2852599cb79469899e0d342b39ed804.png) 绑定输出 ------------ tn2>简单来说就是绑定输入倒过来,你只需要在应用中把消息发送给相关队列其他的你不用管消息应该如何消费。 ![](https://img.tnblog.net/arcimg/hb/11fe6232b67c496ca3b2e54204e7da62.png) tn2>很简单我们再在控制器中添加接口方法,进行发送事件 ```csharp [HttpPost("OutCheck")] public async Task OutRegisterBind([FromServices] DaprClient dapr) { var msg = "9999999"; _log.LogInformation($"发送消息:{msg}"); //组件名 创建操作 消息内容 await dapr.InvokeBindingAsync("myrabbitmq", "create", msg); } ``` ![](https://img.tnblog.net/arcimg/hb/083f1878352040e992bfa40a3956b2c3.png) tn2>由于我输出与输入绑定是在同一个应用上所以立马就处理了。