feignclient url_spring boot使用feignClient调用接口

在我们实际开发过程中,一般都免不了和别的系统做交互,交互肯定少不了数据交换。一般一个系统对应一个数据库。要与另外一个系统的数据做交互,通常的做法是:在另外一个系统中写需要的接口,在需要数据交换的系统中,调用另外一个系统中写好的接口。

Spring boot调用接口我使用过两种方法:1、RestTemplate方法,这种方法使用起来感觉不是很方便,参数不好处理;2、FeignClient,这种方法我比较喜欢,比较符合Spring boot的思想,只需要一点配置,就可以调用另一个系统的接口,而且调用方式和书写Controller比较相似,只是这里的Controller是一个interface。

整个实现过程如下:

1、使用maven构建项目,在pom.xml文件中加入依赖包

1、1 在dependencies加入如下依赖包:

org.springframework.cloud

spring-cloud-starter-feign

1、2 在dependencies后面加入如下依赖:

org.springframework.cloud

spring-cloud-dependencies

Camden.SR5

pom

import

2、编写FeignConfig类。此类的作用是调用接口时一些通用的参数。比如请求头。因为在另一个接口中,可能设置了RequestAttribute参数,那这边调用它的时候就需要以RequestHeader的方式传递。而每个参数就可以放置在FeignConfig中。

如:我地系统中需要一个header参数,我就在这个类中处理。

@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 出现异常:" + response.body().asReader().readText())

}

}!!

}

说明:此类需注解为@Configuration类。

@Value("${tiangu.order.header}"):此参数的值在配置application.yml配置文件中获取,如配置文件值如下:

rainbow:

server:

header: 00101

附上ErrorEntity和ApiUtils代码:

//此类是封装在调用接口出错时显示的错误信息

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 = 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、编写调用另一个接口的interface,这是一个Java接口,里面只声明方法和返回值,不实现。此类可以直接注入到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 {

//传递一个参数

@RequestMapping("/api/v1/test", method = arrayOf(RequestMethod.GET))

fun getList(@RequestParam("mobile") mobile: String): Any

//传递两个参数

@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): Any

//传递两个参数,并且有默认值

@RequestMapping("/api/v1/test4", method = arrayOf(RequestMethod.GET))

fun getAll(@RequestParam("mobile") mobile: String, @RequestParam(name = "type", defaultValue = "") type: String): Any

//传递地址参数和map

@RequestMapping("/api/v1/test5/{no}/pay", method = arrayOf(RequestMethod.PUT))

fun pay(@PathVariable(value = "no") no: String, @RequestBody params: Map): Any

//传递带有请求头参数和map

@RequestMapping("/api/v1/order", method = arrayOf(RequestMethod.GET))

fun getList(@RequestHeader(value = "RAINBOW-API-ID") username: String, @RequestParam queryMap: Map): Any

@RequestMapping("/api/v1/test5/{no}/out", method = arrayOf(RequestMethod.PUT))

fun out(@PathVariable(value = "no") no: String, @RequestBody params: Map): Any

}

说明:@FeignClient("rainbow", url = "${rainbow.server.url}", configuration = arrayOf(FeignConfig::class))

"rainbow"为这个调用的名称,可自定义;url为从配置文件中获取值;configuration固定写法。

@RequestMapping("/api/v1/test", method = arrayOf(RequestMethod.GET))

@RequestMapping中的/api/v1/test是另一个接口中Controller中的地址,它和FeignClient中的url = "${rainbow.server.url}"地址拼接成一个完整的请求地址。method为调用接口那一方的请求方法,要与那边一致。

传递的请求参数:@PathVariable,@RequestParam, @RequestBody 三种传递参数类型,注意:@PathVariable,@RequestParam这两种传递单个参数时,需要注明参数名称,也就是参数里的value值不能省略,否则会报错,我的是这样子的。如:@PathVariable(value = "no") no: String ,@RequestParam("mobile") mobile: String。

4、使用

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

@Autowired

lateinit private var userClient: UserClient

//直接调用

userClient.login(xxx,xxxx)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot,可以使用RestTemplate或FeignClient调用内部的RESTful API。以下是两种方法的示例。 使用RestTemplate 首先需要在Spring Boot项目引入RestTemplate依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 然后在代码使用RestTemplate来调用内部的RESTful API: ```java @RestController public class MyController { @Autowired private RestTemplate restTemplate; @GetMapping("/myapi") public String myApi() { String result = restTemplate.getForObject("http://localhost:8080/internal-api", String.class); return result; } } ``` 在这个例子,RestTemplate被注入到了控制器,并且使用getForObject方法来调用内部的RESTful API。 使用FeignClient FeignClient是一个声明式的HTTP客户端,它可以轻松地定义和调用RESTful API。首先需要在Spring Boot项目引入FeignClient依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 然后在代码声明一个FeignClient接口: ```java @FeignClient(name = "my-service", url = "http://localhost:8080") public interface MyApiClient { @GetMapping("/internal-api") String getInternalApi(); } ``` 在这个例子,@FeignClient注解指定了待调用的服务名和服务地址,并且定义了一个getInternalApi方法来调用内部的RESTful API。 最后在控制器注入MyApiClient接口调用getInternalApi方法即可: ```java @RestController public class MyController { @Autowired private MyApiClient myApiClient; @GetMapping("/myapi") public String myApi() { String result = myApiClient.getInternalApi(); return result; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值