Java
ទំព័រនេះត្រូវបានបកប្រែពីភាសាអង់គ្លេស។ ប្រសិនបើទាំងពីរខុសគ្នា ទំព័រភាសាអង់គ្លេសគឺត្រឹមត្រូវ។ អានទំព័រភាសាអង់គ្លេស
បណ្ណាល័យ Java គឺ com.getlingara:lingara-java នៅលើ Maven Central។ វាត្រូវការ Java 17 ឬថ្មីជាងនេះ ហើយប្រើ java.net.http.HttpClient ផ្ទាល់របស់ JDK ជាមួយ Jackson សម្រាប់ JSON។
របៀបប្រើវា
- ការហៅគឺធ្វើសមកាលកម្ម។ សម្រាប់ការហៅច្រើនក្នុងពេលតែមួយ ដំណើរការពួកវានៅលើ virtual thread ឬ executor មួយ។
- ស្ទ្រីមគឺជា
EventStreamដែលជាទាំងIterableនិងAutoCloseable៖ អានវាដោយរង្វិលជុំforនៅក្នុង try-with-resources។ ព្រឹត្តិការណ៍គឺជា record នៅក្រោម sealed interface ដូច្នេះswitchលើពួកវាគ្របដណ្តប់គ្រប់ករណី។ - ដើម្បីបោះបង់ សូមរំខាន thread ឬហៅ
close()ពី thread ផ្សេង។ បន្ទាប់មកការហៅនឹងបោះCancellationExceptionដែលមិនមែនជាកំហុសណាមួយរបស់បណ្ណាល័យទេ។ - កំហុសពង្រីកពី
LingaraExceptionដែលជា unchecked exception។retryAfter()ត្រឡប់Optional<Duration>។ - បង្កើតក្លាយអិនដោយ
LingaraClient.builder()។ ការហៅដែលមិនស្ទ្រីមគ្មានការកំណត់ពេលទេ រហូតដល់អ្នកកំណត់requestTimeout។
គំរូខាងក្រោមបន្ថែមការពឹងផ្អែក បង្កើតក្លាយអិន ស្ទ្រីមបញ្ជីវាក្យសព្ទ និងដោះស្រាយកំហុសមួយ។
Java
<dependency>
<groupId>com.getlingara</groupId>
<artifactId>lingara-java</artifactId>
<version>0.1.0-alpha.6</version>
</dependency>Java
import com.getlingara.client.LingaraClient;
LingaraClient client =
LingaraClient.builder()
.clientCredentials(
System.getenv("LINGARA_CLIENT_ID"), System.getenv("LINGARA_CLIENT_SECRET"))
.build();Java
import com.getlingara.client.model.GenerateVocabularyEvent;
import com.getlingara.client.model.VocabRequest;
VocabRequest request = new VocabRequest().level(2).sourceLang("en").targetLang("zh").count(8);
try (EventStream<GenerateVocabularyEvent> stream = client.generateVocabulary(request)) {
for (GenerateVocabularyEvent event : stream) {
if (event instanceof GenerateVocabularyEvent.Item item) {
System.out.println(item.data().getWord() + " " + item.data().getTranslation());
}
}
}Java
try {
client.getUsage();
} catch (LingaraException e) {
if (e instanceof ApiException api) {
// A refusal from the API: status(), code() (stable) and getMessage() (localised).
System.out.println(api.status() + " " + api.code() + " " + api.getMessage());
api.retryAfter().ifPresent(wait -> System.out.println("retry after " + wait));
} else if (e instanceof OAuthException oauth) {
// The token endpoint refused the credentials or the scopes.
System.out.println(oauth.status() + " " + oauth.error() + " " + oauth.description());
} else if (e instanceof MaintenanceException maintenance) {
System.out.println("under maintenance");
maintenance.retryAfter().ifPresent(wait -> System.out.println("retry after " + wait));
} else if (e instanceof TransportException transport) {
// No usable answer: CONNECT, TLS, RESET, TIMEOUT, and so on.
System.out.println("transport: " + transport.kind());
}
}
// An interrupted call throws java.util.concurrent.CancellationException instead.