声明式客户端
启动类使用@EnableFeignClients 开启feign的远程调用
使用@FeignClient指定远程调用的微服务,demo如下
package com.atguigu.order.feign;
import com.atguigu.order.feign.fallback.ProductFeignClientFallback;
import com.atguigu.product.bean.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "service-product") // feign客户端,自动去注册中心获取对应的地址
public interface ProductFeignClient {
//mvc注解的两套使用逻辑
//1、标注在Controller上,是接受这样的请求
//2、标注在FeignClient上,是发送这样的请求
@GetMapping("/product/{id}")
Product getProductById(@PathVariable("id") Long id);//将返回的json转化为product
}
controller调用此接口即可实现远程调用 feign的远程调用自动实现了负载均衡
请求第三方api
第三方api不存在于我们的注册中心,阅读第三方文档指定url并携带参数发送请求
package com.atguigu.order.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
// 指定了url,则向url发送请求,没指定,则连注册中心寻找对应的微服务
@FeignClient(value = "weather-client", url = "http://aliv18.data.moji.com")
public interface WeatherFeignClient {
//拼接请求路径
@PostMapping("/whapi/json/alicityweather/condition")
String getWeather(@RequestHeader("Authorization") String auth,
@RequestParam("token") String token,
@RequestParam("cityId") String cityId);
}
测试
package com.atguigu.order;
import com.atguigu.order.feign.WeatherFeignClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class WeatherTest {
@Autowired
WeatherFeignClient weatherFeignClient;
@Test
void test01(){
String weather = weatherFeignClient.getWeather("APPCODE 93b7e19861a24c519a7548b17dc16d75",
"50b53ff8dd7d9fa320d3d3ca32cf8ed1",
"2182");
System.out.println("weather = " + weather);
}
}
小技巧:如何编写好OpenFeign声明式的远程调用接口 • 业务API:直接复制对方Controller签名即可 • 第三方API:根据接口文档确定请求如何发