spring boot使用feignClient調(diào)用接口

在我們實際開發(fā)過程中,一般都免不了和別的系統(tǒng)做交互,交互肯定少不了數(shù)據(jù)交換。一般一個系統(tǒng)對應(yīng)一個數(shù)據(jù)庫。要與另外一個系統(tǒng)的數(shù)據(jù)做交互,通常的做法是:在另外一個系統(tǒng)中寫需要的接口,在需要數(shù)據(jù)交換的系統(tǒng)中,調(diào)用另外一個系統(tǒng)中寫好的接口。

Spring boot調(diào)用接口我使用過兩種方法:1、RestTemplate方法,這種方法使用起來感覺不是很方便,參數(shù)不好處理;2、FeignClient,這種方法我比較喜歡,比較符合Spring boot的思想,只需要一點配置,就可以調(diào)用另一個系統(tǒng)的接口,而且調(diào)用方式和書寫Controller比較相似,只是這里的Controller是一個interface。

整個實現(xiàn)過程如下:

1、使用maven構(gòu)建項目,在pom.xml文件中加入依賴包

1、1 在dependencies加入如下依賴包:
 <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-feign</artifactId>
 </dependency>
1、2 在dependencies后面加入如下依賴:
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2、編寫FeignConfig類。此類的作用是調(diào)用接口時一些通用的參數(shù)。比如請求頭。因為在另一個接口中,可能設(shè)置了RequestAttribute參數(shù),那這邊調(diào)用它的時候就需要以RequestHeader的方式傳遞。而每個參數(shù)就可以放置在FeignConfig中。
如:我地系統(tǒng)中需要一個header參數(shù),我就在這個類中處理。

@Configuration
class FeignConfig {

    @Value("\${rainbow.server.header}")
    lateinit private var header: String

    @Autowired
    lateinit private var utils: ApiUtils

    @Bean
    @Scope("prototype")
    fun feignBuilder() = Feign.builder().decode404().requestInterceptor {
        it.header("Rainbow-APP-ID", header)
    }.errorDecoder { s, response ->
        if (response.status() in 400..499) {
            if (response.body() != null) {
                val error = utils.mapper.readValue(response.body().asInputStream(), ErrorEntity::class.java)
                throw AppException(error.message, HttpStatus.valueOf(error.status))
            }
            val status = HttpStatus.valueOf(response.status())
            throw AppException(status.reasonPhrase, status)
        } else {
            throw Exception("$s 出現(xiàn)異常:" + response.body().asReader().readText())
        }
    }!!       
 }

說明:此類需注解為@Configuration類。
@Value("${tiangu.order.header}"):此參數(shù)的值在配置application.yml配置文件中獲取,如配置文件值如下:
rainbow:
server:
header: 00101

附上ErrorEntity和ApiUtils代碼:

//此類是封裝在調(diào)用接口出錯時顯示的錯誤信息
import com.fasterxml.jackson.annotation.JsonFormat
import org.springframework.http.HttpStatus
import java.util.*
import javax.servlet.http.HttpServletRequest

class ErrorEntity() {
    var message: String? = null
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    val timestamp = Date()
    var status = HttpStatus.BAD_REQUEST.value()
    var error: String? = null
    var path: String? = null
    var code: String? = null

    constructor(code: String, message: String, status: HttpStatus, request: HttpServletRequest) : this() {
        this.code = code
        this.message = message
        this.status = status.value()
        this.error = status.reasonPhrase
        this.path = request.requestURI
    }
}
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.http.converter.StringHttpMessageConverter
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.stereotype.Component
import com.fasterxml.jackson.dataformat.xml.XmlMapper

@Component
open class ApiUtils {
    val restTemplate by lazy {
        RestTemplateBuilder().additionalMessageConverters(
            StringHttpMessageConverter(Charsets.UTF_8),
            MappingJackson2HttpMessageConverter()
        ).build()!!
    }

    val mapper by lazy { ObjectMapper() }

    val objectMapper by lazy { ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)!! }

    val xmlMapper by lazy { XmlMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)!! }

    fun buildUri(url: String, params: Map<String, Any?> = emptyMap()): String {
        val query = params.filterValues { it != null }.map { "${it.key}=${it.value}" }.joinToString("&")
        val sep = if (url.contains("?")) "&" else "?"
        return "$url$sep$query"
    }
}

3、編寫調(diào)用另一個接口的interface,這是一個Java接口,里面只聲明方法和返回值,不實現(xiàn)。此類可以直接注入到service和Controller中使用。

import org.springframework.cloud.netflix.feign.FeignClient
import org.springframework.web.bind.annotation.*

@FeignClient("rainbow", url = "\${rainbow.server.url}", configuration = arrayOf(FeignConfig::class))
interface OrderClient {

//傳遞一個參數(shù)
    @RequestMapping("/api/v1/test", method = arrayOf(RequestMethod.GET))
    fun getList(@RequestParam("mobile") mobile: String): Any


    //傳遞兩個參數(shù)
    @RequestMapping("/api/v1/test2", method = arrayOf(RequestMethod.POST))
    fun getOrRefuse(@RequestParam("no") no: String, @RequestParam("type") type: Int): Any


    //傳遞一個map
    @RequestMapping("/api/v1/test3", method = arrayOf(RequestMethod.POST))
    fun take(@RequestBody params: Map<String, String>): Any


    //傳遞兩個參數(shù),并且有默認(rèn)值
    @RequestMapping("/api/v1/test4", method = arrayOf(RequestMethod.GET))
    fun getAll(@RequestParam("mobile") mobile: String, @RequestParam(name = "type", defaultValue = "") type: String): Any

     //傳遞地址參數(shù)和map
    @RequestMapping("/api/v1/test5/{no}/pay", method = arrayOf(RequestMethod.PUT))
    fun pay(@PathVariable(value = "no") no: String, @RequestBody params: Map<String, Any>): Any

    //傳遞帶有請求頭參數(shù)和map
    @RequestMapping("/api/v1/order", method = arrayOf(RequestMethod.GET))
    fun getList(@RequestHeader(value = "RAINBOW-API-ID") username: String, @RequestParam queryMap: Map<String, String>): Any

    @RequestMapping("/api/v1/test5/{no}/out", method = arrayOf(RequestMethod.PUT))
    fun out(@PathVariable(value = "no") no: String, @RequestBody params: Map<String, Any>): Any

}

說明:@FeignClient("rainbow", url = "${rainbow.server.url}", configuration = arrayOf(FeignConfig::class))
"rainbow"為這個調(diào)用的名稱,可自定義;url為從配置文件中獲取值;configuration固定寫法。
@RequestMapping("/api/v1/test", method = arrayOf(RequestMethod.GET))
@RequestMapping中的/api/v1/test是另一個接口中Controller中的地址,它和FeignClient中的url = "${rainbow.server.url}"地址拼接成一個完整的請求地址。method為調(diào)用接口那一方的請求方法,要與那邊一致。
傳遞的請求參數(shù):@PathVariable,@RequestParam, @RequestBody 三種傳遞參數(shù)類型,注意:@PathVariable,@RequestParam這兩種傳遞單個參數(shù)時,需要注明參數(shù)名稱,也就是參數(shù)里的value值不能省略,否則會報錯,我的是這樣子的。如:@PathVariable(value = "no") no: String ,@RequestParam("mobile") mobile: String。


4、使用
直接注入到service中,即可使用。如下:

@Autowired
    lateinit private var userClient: UserClient

//直接調(diào)用
userClient.login(xxx,xxxx)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,401評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,011評論 3 413
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,263評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,543評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,323評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,874評論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,968評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,095評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,605評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,551評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,720評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,242評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,961評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,358評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,612評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,330評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,690評論 2 370

推薦閱讀更多精彩內(nèi)容