1. 程式人生 > 其它 >Pta6-8次題目集總結

Pta6-8次題目集總結

Feign

宣告式的http客戶端,協助完成http請求的傳送

匯入Maven依賴

<!--        feign客戶端依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

啟動類開啟註解

編寫Java程式碼

package cn.itcast.order.clients;

import cn.itcast.order.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author Pickle
 * @version V1.0
 * @date 2022/12/10 21:40
 */

@FeignClient(name = "/userservice")
public interface UserClient {
    @GetMapping(value = "/user/{id}")
    User findById(@PathVariable(value = "id") Long id);
}

傳送Http請求

    @Autowired
    private UserClient userClient;

    public Order queryOrderById(Long orderId) {
        Order order = orderMapper.findById(orderId);

        //利用Feign傳送http請求
        final User user = userClient.findById(order.getUserId());

        order.setUser(user);

        return order;
    }

自定義Feign配置

  1. application.yml配置

全域性配置

feign:
  client:
    config:
      default:
        loggerLevel: FULL

單個服務配置

feign:
  client:
    config:
      服務名稱:
        loggerLevel: FULL
  1. Java程式碼配置

配置程式碼

package cn.itcast.order.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;

/**
 * @author Pickle
 * @version V1.0
 * @date 2022/12/11 9:54
 */
public class DefaultFeignConfiguration {
    @Bean
    public Logger.Level loggerLevel(){
        return Logger.Level.BASIC;
    }
}

單個service有效

全域性有效

Feign的效能優化-連線池的配置

  1. 引入依賴
<!--        httpClient的依賴-->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>		
  1. 配置連線池
feign:
  httpclient:
    enabled: true # Enables the use of the Apache HTTP Client by Feign
    max-connections: 200 # 最大連線數
    max-connections-per-route: 50 # 單個路徑的最大連線數

Feign抽取Client

將Feign的Client抽取為獨立模組,並且把介面有關的PoJo,預設的Feign配置都放到這個模組中,提供給所有消費者使用。

  1. 將feign獨立成一個moudel
  1. 新增feign-api的依賴
        <dependency>
            <groupId>cn.itcast.demo</groupId>
            <artifactId>feign-api</artifactId>
            <version>1.0</version>
        </dependency>
  1. 將Client加入Spring容器中

因為消費者的啟動類並不會將Client的例項加入到容器中所以要通過配置的方式將Client加入到Spring容器中。

  1. 方案一

消費者的啟動類中直接在註解中說明要掃描的包

  1. 方案二

直接指定位元組碼