springboot使用feign调用不依赖cloud

在使用spring boot调用第三方api中,常用的是okhttp、apache http client等,但是直接使用下来还是有点繁琐,需要手动转换实体。

在springcloud中有个openfeign调用,第一次体验到调用接口还能这么丝滑。注解写道接口上,配置一下,其他交给框架处理。搜了一下这种方式叫做声明式调用。类似的还有Retrofit、forest框架。

openfeign集成到springboot中有何优点:openfeign吸收了Retrofit框架的优点,做了声明式API,但是没有Retrofit多余的Call层。forest是一款国产优秀的框架,单独使用问题不大,但对于后续升级到cloud的boot项目,共存时存在不少问题,并且对上传大文件部分场景的支持有点问题。

这里分两步,先介绍@RequestLine注解调用,后介绍@GetMapping的spring注解调用。

一、传统注解@RequestLine调用

1.加依赖

        <!-- feign -->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>11.0</version>
        </dependency>
        <dependency>
            <groupId>com.netflix.feign</groupId>
            <artifactId>feign-jackson</artifactId>
            <version>8.18.0</version>
        </dependency>

2.写代码

以天气api接口为例

controller层

package com.vvvtimes.demo.controller;

import com.vvvtimes.demo.common.dto.RestResponse;
import com.vvvtimes.demo.domain.dto.WeatherCityDTO;
import com.vvvtimes.demo.domain.mybatis.City;
import com.vvvtimes.demo.domain.vo.WeatherVo;
import com.vvvtimes.demo.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/weather")
public class WeatherController {

    @Autowired
    private WeatherService weatherService;

    @RequestMapping(value = "city/{id:1[0-9]{8}}", method = {RequestMethod.POST, RequestMethod.GET})
    public RestResponse<WeatherVo> loadApi(@PathVariable("id") String id) {
        return weatherService.loadApi(id);
    }


}

service层

/**
     * 获取数据
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "weather_cache", key = "#id")// 从缓存获取,key为ID,缓存具体看 ehcache.xml 配置文件
    public RestResponse<WeatherVo> loadApi(String id) {
        RestResponse<WeatherVo> result =new RestResponse<>();
        WeatherVo weatherVo = sojsonApiClient.getCityWeather(id);
        if(weatherVo!=null && weatherVo.isSuccess()){
            result.setResult(weatherVo);
        }
        return result;
    }

//client层

package com.vvvtimes.demo.client;

import com.vvvtimes.demo.domain.vo.WeatherVo;
import feign.Param;
import feign.RequestLine;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Map;

@Component
public interface SojsonApiClient {

    //@GetMapping(value = "/api/weather/city/{id}")
    @RequestLine("GET /api/weather/city/{id}")
    WeatherVo getCityWeather(@Param("id") String id);

}

client拦截器

package com.vvvtimes.demo.client.interception;

import feign.RequestInterceptor;
import feign.RequestTemplate;

public class SojsonInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {

    }
}

feign配置

package com.vvvtimes.demo.config;

import com.vvvtimes.demo.client.IpinfoApiClient;
import com.vvvtimes.demo.client.SojsonApiClient;
import com.vvvtimes.demo.client.interception.IpinfoInterceptor;
import com.vvvtimes.demo.client.interception.SojsonInterceptor;
import feign.Feign;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApiRegisterConfig {

    @Value("${sojson.base.url:http://t.weather.sojson.com/}")
    private String sojsonRegisterUrl;



    @Bean
    public SojsonApiClient sojsonApiRegister() {
        return Feign.builder().encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .requestInterceptor(new SojsonInterceptor())
                .target(SojsonApiClient.class, sojsonRegisterUrl);
    }


}

3.测试访问

http://localhost:9000/weather/city/101010100

二、spring注解@GetMapping使用

上面使用的注解多少有点别扭,实际上我们可以通过feign-contract Feign的契约方式来使用spring的注解。

这里只对比上的代码讲解改造过程,不给出全代码

1.改造依赖

上面的feign依赖替换如下
 

      <!-- feign -->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>11.6</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-spring4</artifactId>
            <version>11.6</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-jackson</artifactId>
            <version>11.6</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
            <version>11.6</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form</artifactId>
            <version>3.8.0</version>
        </dependency>

2.配置契约

ApiRegisterConfig的Bean加一句.contract(new SpringContract())

对应bean代码如下

    @Bean
    public SojsonApiClient sojsonApiRegister() {
        return Feign.builder().encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .requestInterceptor(new SojsonInterceptor())
                .contract(new SpringContract())
                .target(SojsonApiClient.class, sojsonRegisterUrl);
    }

3.改注解

将@RequestLine注解改成@GetMapping注解,代码如下

    @GetMapping(value = "/api/weather/city/{id}")
        //@RequestLine("GET /api/weather/city/{id}")
    WeatherVo getCityWeather(@PathVariable("id") String id);

至此改造完成。

注意:本文没有设置feign的全局拦截器,因为在第三方接口中,每种接口的鉴权方式不一样,建议每种类型的接口单独设置拦截器做鉴权

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: springboot feign调用例子可以这样:1. 创建一个FeignClient接口,定义要调用的远程接口:@FeignClient("springboot-service") public interface SpringbootService { @RequestMapping("/hello") String hello(); }2. 在需要调用的地方注入FeignClient接口:@Autowired private SpringbootService springbootService;3. 调用远程接口:String result = springbootService.hello(); ### 回答2: Spring Boot Feign 是一种用于简化 RESTful 服务调用的声明式 HTTP 客户端。下面是一个简单的基于 Spring Boot Feign调用示例。 首先,需要在项目的 pom.xml 文件中添加FeignSpring Cloud 相关的依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 然后,在主启动类上添加 `@EnableFeignClients` 注解以启用 Feign 客户端: ```java @SpringBootApplication @EnableFeignClients public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 接下来,创建一个 Feign 客户端接口,并使用 `@FeignClient` 注解指定要调用的远程服务: ```java @FeignClient(name = "remote-service") public interface RemoteServiceClient { @GetMapping("/api/user/{id}") UserDTO getUserById(@PathVariable Long id); } ``` 在上述示例中,我们创建了一个名为 `RemoteServiceClient` 的 Feign 客户端接口,并指定其调用的远程服务名称为 "remote-service"。接口中的 `getUserById` 方法用于调用 "remote-service" 服务的 "/api/user/{id}" 接口,并接收一个路径变量 id,返回类型为 UserDTO。 最后,在需要调用远程服务的地方注入 `RemoteServiceClient` 客户端接口,并使用它进行调用: ```java @RestController public class UserController { @Autowired private RemoteServiceClient remoteServiceClient; @GetMapping("/user/{id}") public UserDTO getUserById(@PathVariable Long id) { return remoteServiceClient.getUserById(id); } } ``` 在上述示例中,我们在 UserController 中注入了 `RemoteServiceClient` 客户端接口,并使用调用远程服务的 getUserById 方法,返回结果作为该接口的返回值。 通过以上步骤,就可以完成一个简单的 Spring Boot Feign 调用示例。注意,还需要配置远程服务的地址和端口等相关配置。 ### 回答3: Spring Boot Feign是一个基于HTTP请求的声明式Web Service客户端。它使用注解方式声明和配置对其他服务的调用,并且提供了一些便捷的功能,使得与其他服务的通信更加简单高效。下面是一个关于使用Spring Boot Feign调用例子。 首先,我们需要在项目的pom.xml文件中添加Feign依赖。 ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.3.RELEASE</version> </dependency> ``` 然后,在启动类上添加@EnableFeignClients注解以启动Feign功能。 ```java @SpringBootApplication @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 接下来,我们创建一个Feign接口,并使用@FeignClient注解指定要调用的服务的名称和URL。 ```java @FeignClient(name = "example-service", url = "http://localhost:8080") public interface ExampleFeignClient { @GetMapping("/example") String getExample(); } ``` 在上面的例子中,我们声明了一个名为ExampleFeignClientFeign接口,它会调用一个名为example-service的服务,并且该服务的URL是http://localhost:8080。 最后,我们可以在其他组件中使用ExampleFeignClient接口来进行调用。 ```java @RestController public class ExampleController { private final ExampleFeignClient exampleFeignClient; public ExampleController(ExampleFeignClient exampleFeignClient) { this.exampleFeignClient = exampleFeignClient; } @GetMapping("/example-feign") public String invokeExampleService() { return exampleFeignClient.getExample(); } } ``` 上面的例子中,我们在ExampleController中注入了ExampleFeignClient接口,在调用invokeExampleService方法时,实际上是调用了ExampleFeignClient接口中的getExample方法。 这就是一个简单的Spring Boot Feign调用例子。使用Feign能够简化微服务之间的通信,提高开发效率。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值