Tutorial/Java และ Spring Boot

อัตราแลกเปลี่ยนใน Java และ Spring Boot

สร้าง client ที่มี type ด้วย RestClient, BigDecimal และ key จาก environment

MMexchangerate.dev·Jul 17, 2026·อ่าน 6 นาที

Spring RestClient แปลง JSON เป็น record ได้ เก็บอัตราเป็น BigDecimal และรักษา source, market_session, data_updated_at

Key points
ใช้ Spring RestClient
ใช้ BigDecimal
อ่าน key จาก EXCHANGERATE_API_KEY
เก็บ data_updated_at

สร้าง RestClient ที่มี type

record เก็บแผนที่อัตราและข้อมูลที่ใช้ตีความ โดย Jackson map snake_case ผ่าน @JsonProperty

java · ExchangeRateClient.javacopy
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

yaml · application.yamlcopy
exchangerate:
  api-key: ${EXCHANGERATE_API_KEY}

จัดการความใหม่และข้อผิดพลาดให้ชัดเจน

RestClient.retrieve() โยนข้อผิดพลาดเมื่อเป็น 4xx หรือ 5xx ตั้ง timeout และ retry เฉพาะความผิดพลาดชั่วคราว

ใช้ BigDecimal ตลอดการคำนวณ
รักษาความละเอียดของอัตราและปัดเฉพาะยอดสุดท้าย
  • ใช้ client ร่วมกัน
  • ตั้ง timeout
  • แคชเฉพาะผลสำเร็จ
  • เก็บแหล่งที่มาและเวลา
MM
exchangerate.dev
คู่มือเชื่อมต่อสำหรับนักพัฒนาที่ใช้ข้อมูล FX

Keep reading

Guideข้อมูล FX ย้อนหลังในคำขอเดียวRead Referenceอ่าน source และ market_sessionRead Guideอัตราเพื่ออ้างอิงและอัตราที่ซื้อขายได้Read