SpringBoot整合原生OpenFegin的坑(非SpringCloud)

冰河團隊發表於2020-10-26

寫在前面

最近,在使用SpringBoot+K8S開發微服務系統,既然使用了K8S,我就不想使用SpringCloud了。為啥,因為K8S本身的就提供了非常6的服務註冊與發現、限流、熔斷、負載均衡等等微服務需要使用的技術,那我為啥還要接入SpringCloud呢?額,說了這麼多,在真正使用SpringBoot+K8S這一套技術棧的時候,也會遇到一些問題,比如我不需要使用SpringCloud時,呼叫其他服務時,我使用的是原生的OpenFegin,在使用OpenFegin呼叫其他服務的時候,就遇到了一個大坑。通過OpenFeign請求返回值LocalDateTime發生了異常,今天,我們就來說說這個坑!

專案整合OpenFegin

整合OpenFegin依賴

首先,我先跟大家說下專案的配置,整體專案使用的SpringBoot版本為2.2.6,原生的OpenFegin使用的是11.0,我們通過如下方式在pom.xml中引入OpenFegin。

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <skip_maven_deploy>false</skip_maven_deploy>
    <java.version>1.8</java.version>
    <openfegin.version>11.0</openfegin.version>
</properties>
<dependencies>
    <dependency>
        <groupId>io.github.openfeign</groupId>
        <artifactId>feign-core</artifactId>
        <version>${openfegin.version}</version>
    </dependency>

    <dependency>
        <groupId>io.github.openfeign</groupId>
        <artifactId>feign-jackson</artifactId>
        <version>${openfegin.version}</version>
    </dependency>
</dependencies>

這裡,我省略了一些其他的配置項。

接下來,我就開始在我的專案中使用OpenFegin呼叫遠端服務了。具體步驟如下。

實現遠端呼叫

首先,建立OpenFeignConfig類,配置OpenFegin預設使用的Contract。

@Configuration
public class OpenFeignConfig {
	@Bean
	public Contract useFeignAnnotations() {
		return new Contract.Default();
	}
}

接下來,我們寫一個通用的獲取OpenFeign客戶端的工廠類,這個類也比較簡單,本質上就是以一個HashMap來快取所有的FeginClient,這個的FeginClient本質上就是我們自定義的Fegin介面,快取中的Key為請求連線的基礎URL,快取的Value就是我們定義的FeginClient介面。

public class FeginClientFactory {
	
	/**
	 * 快取所有的Fegin客戶端
	 */
	private volatile static Map<String, Object> feginClientCache = new HashMap<>();
	
	/**
	 * 從Map中獲取資料
	 * @return 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getFeginClient(Class<T> clazz, String baseUrl){
		if(!feginClientCache.containsKey(baseUrl)) {
			synchronized (FeginClientFactory.class) {
				if(!feginClientCache.containsKey(baseUrl)) {
					T feginClient = Feign.builder().decoder(new JacksonDecoder()).encoder(new JacksonEncoder()).target(clazz, baseUrl);
					feginClientCache.put(baseUrl, feginClient);
				}
			}
		}
		return (T)feginClientCache.get(baseUrl);
	}
}

接下來,我們就定義一個FeginClient介面。

public interface FeginClientProxy {
	@Headers("Content-Type:application/json;charset=UTF-8")
	@RequestLine("POST /user/login")
	UserLoginVo login(UserLoginVo loginVo);
}

接下來,我們建立SpringBoot的測試類。

@RunWith(SpringRunner.class)
@SpringBootTest
public class IcpsWeightStarterTest {
	@Test
	public void testUserLogin() {
		ResponseMessage result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://127.0.0.1").login(new UserLoginVo("zhangsan", "123456", 1));
		System.out.println(JsonUtils.bean2Json(result));
	}
}

一切準備就緒,執行測試。麻蛋,出問題了。主要的問題就是通過OpenFeign請求返回值LocalDateTime欄位會發生異常!!!

注:此時異常時,我們在LocalDateTime欄位上新增的註解如下所示。

import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;


@TableField(value = "CREATE_TIME", fill = FieldFill.INSERT)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
private LocalDateTime createTime;

解決問題

問題描述

SpringBoot通過原生OpenFeign客戶端呼叫HTTP介面,如果返回值中包含LocalDateTime型別(包括其他JSR-310中java.time包的時間類),在客戶端可能會出現反序列化失敗的錯誤。錯誤資訊如下:

 Caused by:com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2020-10-07T11:04:32')

問題分析

從客戶端呼叫fegin,也是相當於URL傳參就相當於經過一次JSON轉換,資料庫取出‘2020-10-07T11:04:32’資料這時是時間型別,進過JSON之後就變成了String型別,T就變成了字元不再是一個特殊字元,因此String的字串“2020-10-07T11:04:32”反序列化就會失敗。

問題解決

在專案中增加依賴。

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9.9</version>
</dependency>

注:如果是用的是SpringBoot,並且明確指定了SpringBoot版本,引入jackson-datatype-jsr310時,可以不用指定版本號。

接下來,在POJO類的LocalDateTime型別欄位增加如下註解。

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

新增後的效果如下所示。

import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;


@TableField(value = "CREATE_TIME", fill = FieldFill.INSERT)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime createTime;

此時,再次呼叫遠端介面,問題解決。

重磅福利

微信搜一搜【冰河技術】微信公眾號,關注這個有深度的程式設計師,每天閱讀超硬核技術乾貨,公眾號內回覆【PDF】有我準備的一線大廠面試資料和我原創的超硬核PDF技術文件,以及我為大家精心準備的多套簡歷模板(不斷更新中),希望大家都能找到心儀的工作,學習是一條時而鬱鬱寡歡,時而開懷大笑的路,加油。如果你通過努力成功進入到了心儀的公司,一定不要懈怠放鬆,職場成長和新技術學習一樣,不進則退。如果有幸我們江湖再見!

另外,我開源的各個PDF,後續我都會持續更新和維護,感謝大家長期以來對冰河的支援!!

相關文章