我的ASP.NET Core应用程序运行一个后台任务,该任务在一定时间间隔内从CoinGecko Api请求加密市场数据。我使用SignalR在客户机和服务器之间创建一个开放的连接,这样显示的数据总是最新的,而客户端不必手动从服务器请求。
CoinGecko的费率限制为每分钟50个电话。我想显示4个特定硬币的数据。根据我想要显示的数据,我估计我需要打25个电话才能更新所有信息。我会把电话拆开:
假设我每分钟都打25个电话来更新我的数据,客户端的数量会影响我发出的API调用的数量吗?我猜它不会,因为数据是在后端请求的,然后通过SignalR集线器提供给所有客户端。
CryptoHttpListener.cs (后台任务):
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/simple/price?ids=bitcoin%2Cethereum%2Ccardano%2Cshiba-inu&vs_currencies=usd").Result;
if (response.IsSuccessStatusCode)
{
string data = response.Content.ReadAsStringAsync().Result;
_logger.LogInformation("{data}", data);
cryptoData = JsonConvert.DeserializeObject<CryptoDataModel>(data);
await SendMessage(cryptoData);
}
else
{
_logger.LogError("API call failed");
}
await Task.Delay(10*1000, stoppingToken);
}
}
public async Task SendMessage(CryptoDataModel cryptoData)
{
decimal Bitcoin = cryptoData.Bitcoin.Usd;
decimal Ethereum = cryptoData.Ethereum.Usd;
decimal Cardano = cryptoData.Cardano.Usd;
decimal ShibaInu = cryptoData.ShibaInu.Usd;
await _hubContext.Clients.All.CryptoPriceUpdated(Bitcoin, Ethereum, Cardano, ShibaInu);
}SignalR中心:
public class CryptoPriceHub : Hub<ICryptoPriceClient>
{
}
public interface ICryptoPriceClient
{
Task CryptoPriceUpdated(decimal Bitcoin, decimal Ethereum, decimal Cardano, decimal ShibaInu);
}Index.cshtml
<p id="bitcoin">placeholder text</p>
<p id="ethereum">placeholder text</p>
<p id="cardano">placeholder text</p>
<p id="shibainu">placeholder text</p>
@section Scripts {
<script src="~/lib/aspnet/signalr/dist/browser/signalr.min.js"></script>
<script type="text/javascript">
var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();
connection.on("CryptoPriceUpdated", function (Bitcoin, Ethereum, Cardano, ShibaInu) {
//Update the DOM
console.log(Bitcoin + ' ' + Ethereum + ' ' + Cardano + ' ' + ShibaInu);
document.getElementById("bitcoin").innerText = Bitcoin;
document.getElementById("ethereum").innerText = Ethereum;
document.getElementById("cardano").innerText = Cardano;
document.getElementById("shibainu").innerText = ShibaInu;
});
connection.start();
</script>
}发布于 2021-12-10 18:14:39
您需要确保后端服务器正确地缓存API调用。
如果API结果被缓存在服务器上,缓存的结果用于面向公共请求的对象,那么只有背景中的API调用才会计算到速率限制。
但是,如果每个面向公共的请求都会导致API调用,那么在2个请求之后,您将达到50/min的速率限制。
总结一下:确保服务器正确地缓存API调用。
https://stackoverflow.com/questions/70307329
复制相似问题