在我們實際開發(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)