美文网首页
使用【Feign】调用接口

使用【Feign】调用接口

作者: 冯延龙 | 来源:发表于2019-08-28 11:51 被阅读0次

    使用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 ;
        }
    }
    

    相关文章

      网友评论

          本文标题:使用【Feign】调用接口

          本文链接:https://www.haomeiwen.com/subject/fsdpectx.html