调用第三方接口:springBoot整合forest

Forest是什么?

Forest是一个高层的、极简轻量级 HTTP调用API框架,让Java发送HTTP/HTTPS请求不再难。它比OkHttp和HttpClient更高层,比Feign更轻量,是封装调用第三方restful api client接口的好帮手。

相比于直接使用Httpclient我们不再写一大堆重复的代码了,而是像调用本地方法一样去发送HTTP请求。

springboot整合forst

1、pom.xml中引入依赖

<dependency>
    <groupId>com.dtflys.forest</groupId>
    <artifactId>forest-spring-boot-starter</artifactId>
    <version>1.5.36</version>
</dependency>

2、配置文件yml,添加forest的相关配置

forest:
  max-connections: 1000        # 连接池最大连接数
  connect-timeout: 3000        # 连接超时时间,单位为毫秒
  read-timeout: 3000           # 数据读取超时时间,单位为毫秒

3、建一个Interface

比如命名为MyClient,并创建一个接口方法名为helloForest,用@Get注解修饰之。

public interface MyClient {

    @Get("http://localhost:8080/hello")
    String helloForest();

}

通过@Get注解,将上面的MyClient接口中的helloForest()方法绑定了一个 HTTP 请求, 其 URL 为http://localhost:8080/hello ,并默认使用GET方式,且将请求响应的数据以String的方式返回给调用者。

4、扫描接口 

友情提示:1.5.1以后版本可以跳过此步,不需要 @ForestScan 注解来指定扫描的包范围

若您已有定义好的 Forest 请求接口(比如名为 com.yoursite.client.MyClient),那就可以开始愉快使用它了。

只要在Springboot的配置类或者启动类上加上@ForestScan注解,并在basePackages属性里填上远程接口的所在的包名

@SpringBootApplication
@Configuration
@ForestScan(basePackages = "com.yoursite.client")
public class MyApp {
 ...
}

Forest 会扫描@ForestScan注解中basePackages属性指定的包下面所有的接口,然后会将符合条件的接口进行动态代理并注入到 Spring 的上下文中。

5、发送请求

然后便能在其他代码中从 Spring 上下文注入接口实例,然后如调用普通接口那样调用即可

@Component
public class MyService {
    
    // 注入自定义的 Forest 接口实例
    @Resource
    private MyClient myClient;

    public void testClient() {
        // 调用自定义的 Forest 接口方法
        // 等价于发送 HTTP 请求,请求地址和参数即为 helloForest 方法上注解所标识的内容
        String result = myClient.helloForest();
        // result 即为 HTTP 请求响应后返回的字符串类型数据
        System.out.println(result);
    }

}

详情可查看forest的官方文档:🎁 新手介绍 | Forest (dtflyx.com)

相关推荐

  1. 调用接口springBoot整合forest

    2024-03-28 11:48:03       48 阅读
  2. Springboot整合技术-消息

    2024-03-28 11:48:03       46 阅读
  3. 调用接口-RestTemplate

    2024-03-28 11:48:03       18 阅读
  4. 调用接口-OkHttpClient

    2024-03-28 11:48:03       23 阅读
  5. SpringBoot实现重试调用API

    2024-03-28 11:48:03       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-28 11:48:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-28 11:48:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-28 11:48:03       82 阅读
  4. Python语言-面向对象

    2024-03-28 11:48:03       91 阅读

热门阅读

  1. 使用vue根据表格内容生成Excel表格并下载

    2024-03-28 11:48:03       40 阅读
  2. 网站建设服务器怎么选

    2024-03-28 11:48:03       47 阅读
  3. 函数 GetMemoryType 的理解

    2024-03-28 11:48:03       41 阅读
  4. linux进程切换

    2024-03-28 11:48:03       44 阅读
  5. 【C语言】RC4 测试代码

    2024-03-28 11:48:03       45 阅读
  6. el-upload上传文件前端自己读取excel

    2024-03-28 11:48:03       38 阅读
  7. uniapp H5 开发,公众号时请求跨域了,要用proxy

    2024-03-28 11:48:03       43 阅读
  8. Nginx服务

    2024-03-28 11:48:03       42 阅读