美文网首页
使用Springboot+Feign Clients快速搭建RE

使用Springboot+Feign Clients快速搭建RE

作者: 叩丁狼教育 | 来源:发表于2018-10-31 17:57 被阅读269次

    翻译:叩丁狼教育吴嘉俊

    在本文中,我们会快速的使用Springboot,配合Feign搭建一个简单的REST客户端应用。通过本示例,让大家对这两个框架的配合有一个基本的了解。

    Spring Boot 是一个Java的快速开发框架,用于简化web和企业级应用开发。Spring boot内置tomcat服务器,提供了大量的starter配置,实现多种组件的自动装配。

    Feign 是Netflix提供的一个实现了REST API 客户端的声明式开发框架。Feign允许使用标签注解接口达到声明式的创建REST客户端,具体的实现在运行时提供。

    项目环境

    准备好以下的工具:

    1. JDK 1.8.81
    2. IntelliJ 2018.2.2
    3. Spring Boot 2.0.4
    4. Gradle 4.10
    5. Spring Cloud Finchley.SR1

    创建一个Springboot应用

    在IDEA中File->new->Project:

    image.png

    选择Spring Initializr,并选择一个合适的JDK版本:

    image.png

    指定一个Group和Artiface名字。选择Gradle Project并且输入一个项目的版本。

    image.png

    在接下来的窗口中选择:

    • Core -> DevTools
    • Web -> Web
    • Cloud -> Cloud Bootstrap
    image.png

    最后一步中,为项目选择一个保存地址:

    image.png

    到此为止,我们已经成功创建了一个springboot的基础项目。

    image.png

    编写Controller

    创建一个名叫FeignController的类。将类标记为Controller,并且实现一个返回ResponseEntity的方法,方法标记为接受Get请求。在这个版本中,我们的IWeatherClient返回一个虚拟的数据。

    package com.example.feign.controller;
    
    @RestController
    public class FeignController {
    
        private final IWeatherClient weatherClient;
    
        @Autowired
        public FeignController(IWeatherClient weatherClient) {
            this.weatherClient = weatherClient;
        }
    
        @GetMapping(path = "/weather")
        ResponseEntity<Map> getWeather() {
            return ResponseEntity.ok(weatherClient.getWeather().getBody());
        }
    }
    
    

    在应用的配置文件(application.properties)中,添加服务端口:

    server.port=9090
    
    

    启动应用,访问请求地址:

    image.png

    创建Feign客户端实现

    接下来,我们将上文中虚假的IWeatherClient替换为真实的服务内容。

    在build.gradle文件中添加如下配置:

    compile('org.springframework.boot:spring-boot-starter-web-services')
    compile('org.springframework.cloud:spring-cloud-starter-openfeign')
    compile('org.springframework.cloud:spring-cloud-starter-config')
    
    

    运行Gradle的build任务;

    image.png

    创建一个Feign Client接口,我们命名为IWeatherClient:

    image.png

    在我们的接口中添加一个获取天气的方法,并使用@FeignClient注解将我们的接口创建为一个FeignClient。@FeignClient注解需要目标服务的名字和URL。在这里,我选择data这个名字,并且通过参数传入对应的URL。

    package com.example.feign.feign;
    
    @FeignClient(name = "data", url = "${feign.client.url}")
    public interface IWeatherClient {
    
        @RequestMapping(method = RequestMethod.GET)
        ResponseEntity<Map> getWeather();
    
    }
    
    

    添加一个接口的实现。如果在执行该服务的时候出现错误,我们需要回退(fallback),在示例中,我们不处理任何异常,所以返回一个null。

    package com.example.feign.feign.imp;
    
    @Component
    public class WeatherFallback implements IWeatherClient {
    
        @Override
        public ResponseEntity<Map> getWeather() {
            return null;
        }
    
    }
    
    

    在application.properties文件中添加具体的远端服务地址:

    feign.client.url = https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22
    
    

    我们访问一下这个url地址,以下就是这个服务返回的响应:

    {"coord":{"lon":139.01,"lat":35.02},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":285.514,"pressure":1013.75,"humidity":100,"temp_min":285.514,"temp_max":285.514,"sea_level":1023.22,"grnd_level":1013.75},"wind":{"speed":5.52,"deg":311},"clouds":{"all":0},"dt":1485792967,"sys":{"message":0.0025,"country":"JP","sunrise":1485726240,"sunset":1485763863},"id":1907296,"name":"Tawarano","cod":200}
    
    

    接下来,修改我们的FeignApplication类。在FeignApplication类上添加@EnableFeignClients注解,要求FeignClient扫描指定的包含FeignClient服务的包:

    package com.example.feign;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    
    @SpringBootApplication
    @EnableFeignClients(basePackages = {"com.example.feign.feign",
            "com.example.feign.controller"})
    public class FeignApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(FeignApplication.class, args);
        }
    }
    
    

    再次启动应用,请求/weather,我们就能得到远端服务的内容了:

    image.png

    这个小例子清楚的展示了如何通过Feign创建一个Weather API的HTTP客户端。Feign的核心在于降低基于RESTful 的HTTP API客户端的开发复杂度。

    原文:https://www.javacodegeeks.com/2018/10/making-rest-communication-easy-with-feign-clients.html

    想获取更多技术视频,请前往叩丁狼官网:http://www.wolfcode.cn/openClassWeb_listDetail.html

    相关文章

      网友评论

          本文标题:使用Springboot+Feign Clients快速搭建RE

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