• EnglishEspañol日本語한국어Português
  • 로그인지금 시작하기

사용자의 편의를 위해 제공되는 기계 번역입니다.

In the event of any inconsistency between the English version and the translated version, the English versionwill take priority. Please visit this page for more information.

문제 신고

NerdGraph 튜토리얼: 동시성 제한 처리

New Relic의 NerdGraph API는 사용자당 동시 요청 수를 25개로 제한합니다. 다음 코드 예제는 이러한 제한을 피하거나 HTTP 429 상태 코드를 수신하기 위한 시작점으로 사용할 수 있습니다. 아래의 두 예는 많은 New Relic 계정에 대해 병렬로 쿼리를 실행하는 동일한 사용 사례를 따르지만 여전히 NerdGraph 동시성 제한에 속합니다.

자바스크립트

동시성을 처리하는 한 가지 방법은 작업자 풀을 사용하는 것입니다. 아래 예제에서는 이를 위해 비동기 모듈을 사용합니다. 동시 실행 제한이 설정된 큐를 생성하고, 요청을 해당 큐에 작업으로 푸시하고, 모든 작업이 완료되면 큐를 비웁니다.

import got from 'got';
import async from 'async';
const API_KEY = '<key>' //GraphQL User Key
const MAX_CONCURRENCY = 25; //Maximum amount of requests in queue at a given time
const GRAPH_API = 'https://api.newrelic.com/graphql';
const HEADERS = { 'Content-Type': 'application/json', 'Api-Key': API_KEY };
async function main() {
let accounts = await getAccounts(); //All accounts to run a query against
var allResults = [];
//Queue initialization
const q = async.queue(async (task, cb) => {
let result = await makeRequest(task.acct)
allResults.push({'transactionCount': result[0].count, 'account': task.acct.id});
cb();
}, MAX_CONCURRENCY);
//Push requests on to the queue (one for each account)
accounts.forEach(acct => {
q.push({acct: acct});
});
await q.drain(); //Drain event listener when all tasks are complete
console.log(allResults);
}
async function makeRequest(acct) {
let nrql = `SELECT count(*) FROM Transaction`;
let gql = `{
actor {
account(id: ${acct.id}) {
nrql(query: "${nrql}", timeout: 90) {
results
}
}
}
}`;
let opts = {
url: GRAPH_API,
headers: HEADERS,
json: {'query': gql, 'variables': {}}
};
let response = await got.post(opts).json();
if (!response.errors) {
return response.data.actor.account.nrql.results;
} else {
console.log('Query Error');
console.log(response.errors);
}
}
async function getAccounts() {
var q = `{
actor {
accounts {
id
name
}
}
}`
var opts = {
url: GRAPH_API,
headers: HEADERS,
json: {'query': q, 'variables': {}}
}
let resp = await got.post(opts).json();
return resp.data.actor.accounts;
}
main();

파이썬

다음 패키지를 활용하여 Python을 사용하여 비동기 요청 및 동시성을 처리할 수도 있습니다.

  • aiohttp - 비동기 http 요청을 만드는 데 사용됩니다.
  • asyncio - 동시성을 처리하는 데 사용됩니다.

다음은 동시 동시 요청량을 관리하는 Semaphore를 설정합니다. 그런 다음 asyncio.gather() 사용하여 여러 코루틴을 동시에 실행하고 완료될 때까지 기다립니다.

import aiohttp
import asyncio
API_KEY = '<key>'
MAX_CONCURRENCY = 25
GRAPHQL_API = 'https://api.newrelic.com/graphql'
HEADERS = {'Content-Type': 'application/json', 'Api-Key': API_KEY}
async def main():
#All accounts to run a query against
accounts = await get_accounts()
# Semaphore for controlling concurrency
limit = asyncio.Semaphore(MAX_CONCURRENCY)
#Add all accounts to run a query against
tasks = [send_request(acct, limit) for acct in accounts]
#Schedule all tasks to run concurrently
allResults = await asyncio.gather(*tasks)
print(allResults)
async def send_request(acct, limit):
nrql = "SELECT count(*) FROM Transaction"
gql = f'''
{{
actor {{
account(id: {acct['id']}) {{
nrql(query: "{nrql}", timeout: 90) {{
results
}}
}}
}}
}}
'''
async with limit:
try:
async with aiohttp.ClientSession() as session:
async with session.post(GRAPHQL_API, json={"query": gql, "variables":{}}, headers=HEADERS) as response:
result = await response.json()
return {'transactionCount': result['data']['actor']['account']['nrql']['results'][0]['count'], 'account': acct['id']}
except Exception as error:
print("Query Error")
raise error
async def get_accounts():
gql = """
{
actor {
accounts {
id
name
}
}
}
"""
async with aiohttp.ClientSession() as session:
async with session.post(GRAPHQL_API, json={"query": gql, "variables":{}}, headers=HEADERS) as response:
result = await response.json()
return result['data']['actor']['accounts']
if __name__ == '__main__':
asyncio.run(main()) #Run event loop

NerdGraph 제한에 대한 자세한 내용은 NerdGraph 사용 제한을 참조하세요.

Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.