使用【Feign】调用接口

使用feign能像使用service类一样的方式调用接口,使调用简单明了。
文档:https://cloud.spring.io/spring-cloud-openfeign/reference/html/

添加依赖

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
    ......
}

这里使用的是openfeign,用Spring Initializr生成项目的时候直接勾选就可以,也可以自己添加使用。以前有些项目使用的是spring-cloud-starter-feign使用方法一致。

编写调用接口的FeignClient

@FeignClient(name = "myApi", url = "https://v1.myapi/")
public interface MyApi {
    @GetMapping("search")
    ResultMyApi searchApiList(@SpringQueryMap SearchParameter parameter);
}


@Data
public class SearchParameter {
    private String keyword;
    private String type;
    private Integer pageSize;
    private Integer page;
}

新建一个interface使用注解@FeignClient示例中是直接通过接口地址调用,要指定name
另一种方式是使用Eureka服务发现的应用,要调用微服务可以直接指定应该名就可以了@FeignClient("myapi")
interface里面调用search接口的写方和接口的定义几乎一样。示例中用了@SpringQueryMap注解,其作用是动态的添加url后面的参数,如果parameter没有设置的项(如pageSize)会被忽略https://v1.myapi/search?keyword=xxx&type=xxx&page=0

主类添加@EnableFeignClients

@EnableFeignClients
@SpringBootApplication
public class MusicApplication {

    public static void main(String[] args) {
        SpringApplication.run(MusicApplication.class, args);
    }

}

在代码中使用API

@Service
public class MyService {
    @Autowired
    private MyApi myApi;

    public ResultMyApi search() {
        SearchParameter parameter = new SearchParameter();
        parameter.setKeyword("xxx");

        ResultMyApi result = myApi.searchApiList(parameter );
        return result ;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容