学習ブログ: [SpringCloud] Feign

Feign とリボンの違いは、Ribbon はマイクロサービス名を使用してアクセスし、RestTemplate を使用して HTTP リクエストをカプセル化するのに対し、Feign はこれに基づいてインターフェイスとアノテーションを使用してリクエストをさらにカプセル化し、HTTP クライアントの作成を容易にすることです。Feign は、Ribbon よりも読みやすいですが、パフォーマンスは低くなります。


プロジェクト構造
ここに画像の説明を挿入

依存関係をインポートする

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>3.1.3</version>
        </dependency>

サービスインターフェース、オープンアノテーション@FeignClient

@FeignClient(value = "http://SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
    
    

    @GetMapping("/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id);

    @GetMapping("/dept/list")
    public List<Dept> queryAll();

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept);
}


プロジェクト構造
ここに画像の説明を挿入
設定ファイル

server:
  port: 80

spring:
  application:
    name: SPRINGCLOUD-CONSUMER-DEPT

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    register-with-eureka: false #不注册到eureka中
  instance:
    instance-id: springcloud-consumer-dept80  #描述信息
    prefer-ip-address: true #优先使用ip注册,访问显示ip

management:
  endpoints:
    web:
      exposure:
        include: "*"
  info:
    env:
      enabled: true

# 暴露端点info
info:
  app.name: yl-springcloud
  company.name: www.yl.com
  build.artifactId: com.yl.springcloud
  build.version: 1.0-SNAPSHOT

コントローラ

@RestController
public class DeptConsumerController {
    
    

    //消费者没有service
    //RestTemplate 直接调用 注册到spring
    //(URL,实体 Map, Class<T>,  responseType)

    @Autowired
    private DeptClientService service = null;

    @GetMapping("/consumer/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id){
    
    
        return this.service.queryById(id);
    }

    @GetMapping("/consumer/dept/list")
    public List<Dept> queryAll(){
    
    
        return this.service.queryAll();
    }

    @PostMapping("/consumer/dept/add")
    public boolean addDept(Dept dept){
    
    
        return this.service.addDept(dept);
    }

}

メインのスタートアップ クラス、オープン アノテーション @EnableFeignClients

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {
    
    "com.yl.springcloud"})
public class FeignDeptConsumer_80 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(FeignDeptConsumer_80.class,args);
    }
}

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/Aurinko324/article/details/125657626