基于Dapr的Dotnet和Java间的服务调用

Java服务端[略]

请参考 Java基于Dapr的服务调用完成Java服务端的搭建

Dotnet客户端

1.创建Dotnet Webapi项目
dotnet new webapi -n dotnet_client_demo --no-https true
2.添加Dapr的ASP.NET依赖,[控制台项目只需要添加Client依赖就可以了]
cd dotnet_client_demo
dotnet add package Dapr.AspNetCore
3.容器中注册
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers().AddDapr();

// ...
4.控制器中使用
using Dapr.Client;
using Microsoft.AspNetCore.Mvc;

namespace dotnet_client_demo.Controllers;

[ApiController]
[Route("[controller]")]
public class ClientController : ControllerBase
{
    private readonly ILogger<ClientController> _logger;
    private readonly DaprClient _client;
    
    private static readonly string SERVICE_APP_ID = "server_demo";
    private static readonly string METHOD_NAME = "hello";
    
    public ClientController(ILogger<ClientController> logger,DaprClient client )
    {
        _logger = logger;
        _client = client;
    }

    [HttpGet("/say")]
    public async Task<string> say() {
        Dictionary<string,object> requestParams = new()
        {
            {"name","fanqi"}
        };
        Dictionary<string, object> response = 
            await _client.InvokeMethodAsync<Dictionary<string,object>,Dictionary<string,object>>(HttpMethod.Post, SERVICE_APP_ID, METHOD_NAME, requestParams);
        return response["data"].ToString();
    }
}
5.配置启动端口

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Urls": "http://*:9999"
}

若无法生效,请查看launchSettings.json是否对运行环境做了端口配置

6.新建启动配置

image

image

dapr run --app-id dotnet_client_demo --app-port 9999 --dapr-http-port 9001 -- dotnet run bin/Debug/net7.0/dotnet_client_demo.dll
7.测试【略】
posted @ 2023-06-09 16:07  SpringCore  阅读(26)  评论(0编辑  收藏  举报