외부 서비스와 연동
Extend Cloud Code modules with external services using NuGet packages or HTTP clients.
읽는 시간 1분최근 업데이트: 한 달 전
Cloud Code 모듈을 외부 서비스와 연동할 수 있습니다. 커스텀 데이터 유형을 처리하기 위해 커스텀 JSON 직렬화를 구현할 수 있습니다.
NuGet 패키지 사용
Cloud Code 모듈은 .NET 생태계에 속한 C# 라이브러리 프로젝트이므로 NuGet 패키지 관리자를 사용하여 종속성을 설치합니다. 즉, Cloud Code 모듈에서 외부 NuGet 패키지를 사용할 수 있습니다. 사용 가능한 NuGet 패키지를 확인하려면 NuGet 패키지 라이브러리를 참고하십시오.외부 API 호출
외부 API를 호출할 수도 있습니다. 아래 샘플은 Cat Facts API를 호출하여 고양이에 관한 무작위 정보를 가져옵니다.-
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}"); } }} -
클래스에서
ModuleConfig클래스를 싱글톤으로 선언합니다.CatFactsApipublic class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi()); }} -
클래스의
CatFactsApi메서드를 호출하는GetCatFact함수를 선언합니다.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()); } }} -
게임 클라이언트에서 함수를 호출합니다. 이 함수는 고양이에 관한 무작위 정보를 반환합니다.
GetCatFact{ "output": { "fact": "The Amur leopard is one of the most endangered animals in the world.", "length": 68 }}