与外部服务集成
Extend Cloud Code modules with external services using NuGet packages or HTTP clients.
阅读时间2 分钟最后更新于 1 个月前
Cloud Code 模块可以与外部服务集成。 要处理自定义数据类型,您可以实现自定义 JSON 序列化。
使用 NuGet 包
Cloud Code 模块是 .NET 生态系统中的 C# 库项目,因此它们使用 NuGet Package Manager 来安装依赖项。这意味着您可以在 Cloud Code 模块中使用任何外部 NuGet 包。 要查看可用的 NuGet 包,请参阅 NuGet 包库。调用外部 API
您还可以调用任何外部 API。以下示例调用 Cat Facts API 来获取随机的 cat fact。-
声明一个 类来处理 API 调用。
CatFactsApiusing Newtonsoft.Json;using RestSharp;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;namespace CatFacts;public interface ICatFactsApi{ public Task<CatFactsApiResponse?> GetCatFact();}public class CatFactsApiResponse{ public string fact { get; set; } public int length { get; set; }}public class CatFactsApi : ICatFactsApi{ private readonly RestClient _httpClient; public CatFactsApi() { // It's important to only create one RestClient per service in order to avoid creating and destroying too many network connections which could hurt performance _httpClient = new RestClient("https://catfact.ninja/fact"); } public async Task<CatFactsApiResponse?> GetCatFact() { var request = new RestRequest(); try { var res = await _httpClient.ExecuteGetAsync(request); return JsonConvert.DeserializeObject<CatFactsApiResponse?>(res.Content); } catch (ApiException e) { throw new Exception($"Failed to get cat fact: {e.Message}"); } }} -
将这个 类声明为
CatFactsApi类中的单例。ModuleConfigpublic class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi()); }} -
声明一个 函数来调用
GetCatFact类的CatFactsApi方法:GetCatFactusing Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;namespace CatFacts;public class CatFactsSample{ private static ILogger<CatFactsSample> _logger; public CatFactsSample(ILogger<CatFactsSample> logger) { _logger = logger; } [CloudCodeFunction("GetCatFact")] public async Task<CatFactsApiResponse?> GetCatFact(ICatFactsApi catFactsApi) { try { var fact = await catFactsApi.GetCatFact(); _logger.LogInformation("Cat fact: {fact}", fact?.fact); return fact; } catch (ApiException e) { _logger.LogError("Failed to get cat fact. Error: {Error}", e.Message); throw new Exception($"Failed to get cat fact: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi()); } }} -
从游戏客户端调用 函数。此函数返回一个随机的 cat fact:
GetCatFact{ "output": { "fact": "The Amur leopard is one of the most endangered animals in the world.", "length": 68 }}