OpenFeign

OpenFeign คือไคลเอนต์เว็บเซอร์วิสแบบประกาศ (declarative) ที่ทำให้การเขียนไคลเอนต์เว็บเซอร์วิสง่ายขึ้น ด้วยการสร้างอินเทอร์เฟซและใส่แอนิเมชัน (annotation) คุณก็สามารถเรียกใช้บริการระยะไกลได้อย่างง่ายดาย

คุณสมบัติหลัก

  • การเขียนโปรแกรมแบบประกาศ: กำหนดไคลเอนต์ HTTP ผ่านอินเทอร์เฟซและแอนิเมชัน
  • การผสานรวมกับ Spring Cloud: ผสานรวมอย่างไร้รอยต่อกับ Spring Cloud LoadBalancer, Eureka, CircuitBreaker ฯลฯ
  • รองรับ Encoder หลายแบบ: รองรับรูปแบบข้อมูล JSON, XML, Form และอื่น ๆ
  • สถาปัตยกรรมแบบปลั๊กอินได้: รองรับ encoder, decoder, interceptor ที่กำหนดเอง ฯลฯ
  • โหลดบาลานซิง: รองรับ Spring Cloud LoadBalancer ในตัว
  • รองรับ Circuit Breaker: ผสานรวมกับ Spring Cloud CircuitBreaker
  • การบันทึก log: รองรับการบันทึก log ในตัวพร้อมระดับ log ที่กำหนดค่าได้
  • รองรับการบีบอัด: รองรับการบีบอัดแบบ GZIP ของคำขอและการตอบกลับ
  • รองรับ OAuth2: รองรับการพิสูจน์ตัวตน OAuth2 ในตัว

เริ่มต้นอย่างรวดเร็ว

เพิ่มการพึ่งพา

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

เปิดใช้ Feign Clients

@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

สร้าง Feign Client

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();
    
    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}

โครงสร้างไดเรกทอรี

แหล่งเรียนรู้

ความเข้ากันได้ของเวอร์ชัน

  • Spring Boot 3.x: ใช้ Spring Cloud 2022.0.x ขึ้นไป
  • Spring Boot 2.x: ใช้ Spring Cloud 2021.0.x และต่ำกว่า

สัญญาอนุญาต

OpenFeign ได้รับอนุญาตภายใต้ Apache License 2.0