本文小編為大家詳細介紹“SpringBoot整合OpenFeign的坑怎么解決”,內容詳細,步驟清晰,細節處理妥當,希望這篇“SpringBoot整合OpenFeign的坑怎么解決”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
首先,我先跟大家說下項目的配置,整體項目使用的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;
此時,再次調用遠程接口,問題解決。
讀到這里,這篇“SpringBoot整合OpenFeign的坑怎么解決”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。