Spring RestClient แปลง JSON เป็น record ได้ เก็บอัตราเป็น BigDecimal ฉีด key จาก configuration และรักษา source, market_session, data_updated_at
ประเด็นสำคัญ
ใช้ Spring
RestClientใช้
BigDecimalอ่าน key จาก
EXCHANGERATE_API_KEYเก็บ
data_updated_atสร้าง RestClient แบบ typed
record เก็บแผนที่อัตราและข้อมูลที่ใช้ตีความ โดย Jackson map snake_case ผ่าน @JsonProperty
package com.example.fx;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
record LatestRates(
String base,
String source,
@JsonProperty("market_session") String marketSession,
@JsonProperty("data_updated_at") Instant dataUpdatedAt,
Map<String, BigDecimal> rates
) {}
@Component
public final class ExchangeRateClient {
private final RestClient client;
public ExchangeRateClient(
RestClient.Builder builder,
@Value("${exchangerate.api-key}") String apiKey
) {
this.client = builder
.baseUrl("https://api.exchangerate.dev/v1")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
.build();
}
public LatestRates latest(String base) {
return client.get()
.uri("/latest/{base}?symbols=EUR,GBP", base)
.retrieve()
.body(LatestRates.class);
}
}โหลด key จาก environment
exchangerate:
api-key: ${EXCHANGERATE_API_KEY}จัดการความใหม่และข้อผิดพลาดให้ชัดเจน
RestClient.retrieve() โยนข้อผิดพลาดเมื่อเป็น 4xx หรือ 5xx ตั้ง timeout และ retry เฉพาะความผิดพลาดชั่วคราว
ใช้ BigDecimal ตลอดการคำนวณ
รักษาความละเอียดของอัตราและปัดเฉพาะยอดสุดท้าย
- ใช้ client ร่วมกัน
- ตั้ง timeout
- แคชเฉพาะผลสำเร็จ
- เก็บแหล่งที่มาและเวลา
ER
exchangerate.dev
คู่มือเชื่อมต่อสำหรับนักพัฒนาที่ใช้ข้อมูล FX
