1.导入OpenFeign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
这里的版本号要注意,需要和SpringBoot版本进行兼容,下面的地址有给出SpringCloud、SpringBoot、SpringCloud Alibaba版本对应的关系。 版本对应关系
2.使用OpenFeign调用Http请求
这里以聚合数据API为例进行测试
根据天气预报接口返回的json数据映射成java类,这里使用的是IDEA GsonFormatPlus 插件
新建WeatherResult类
右键点击Generate
选择GsonFormatPlus
复制json格式数据粘贴到窗口中,点击OK
选择映射的字段
最后点击OK,就生成java字段属性了,结果如下
新建 WeatherFeignClient 接口
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* com.example.learning.feignclient
* Description:
*
* @author jack
* @date 2021/6/20 11:04
*/
@Component
@FeignClient(name = "weather", url = "http://apis.juhe.cn", fallback = WeatherFeignClientFactory.class)
public interface WeatherFeignClient {
/**
* 根据城市名称查询天气预报
*
* @param city 城市名称
* @param key 秘钥
* @return 天气预报
*/
@GetMapping(value = "/simpleWeather/query")
WeatherResult getWeather(@RequestParam(value = "key") String key, @RequestParam(value = "city") String city);
}
新建WeatherFeignClientFactory 调用失败容错
/**
* com.example.learning.feignclient.fallback
* Description:
*
* @author jack
* @date 2021/6/19 17:44
*/
@Component
public class WeatherFeignClientFactory implements WeatherFeignClient {
@Override
public WeatherResult getWeather(String key, String city) {
return null;
}
}
@FeignClient 属性
- url:url一般用于调试,可以手动指定@FeignClient调用的地址
- name:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现
- configuration:Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
- fallback:定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑
- fallbackFactory:工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码
- path: 定义当前FeignClient的统一前缀
3.测试
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
/**
* com.example.learning.feign
* Description:
*
* @author jack
* @date 2021/6/20 11:29
*/
@SpringBootTest
public class WeatherFeignTest {
@Resource
private WeatherFeignClient weatherFeignClient;
@Test
public void getWeather() {
String city = "杭州";
String key = "xxxxx";
WeatherResult weather = weatherFeignClient.getWeather(key, city);
System.out.println(weather);
}
}
调用结果: