码迷,mamicode.com
首页 > 编程语言 > 详细

SpringCloud-Feign第一课-使用示例

时间:2019-07-01 00:52:33      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:param   原理   href   基本   很多   wired   res   功能   一课   

概述

  • Feign 是一个Http客户端框架,可以理解为功能类似并且优于HttpClient框架,其使用方式来说比使用HttpClient更方便,既然是一个Http客户端框架,肯定就可以完成对接口的请求了,那么接下来就用一个示例来展示一下Feign如何使用

    Feign简单的使用示例

    构建一个SpringBoot Web服务端
@RestController
public class HelloWorldController {
    @GetMapping("/test")
    public String test(@RequestParam("p1") String p1,@RequestParam("p2") String p2){
        return "123";
    }
}
  • 关于如何构建一个SpringBoot Web项目就不再具体介绍,请直接参考

    构建一个SpringCloud 客户端
  • 构建一个Spring Boot
  • 在pim中添加Spring Cloud依赖
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>9.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-slf4j</artifactId>
            <version>9.7.0</version>
        </dependency>
  • 在入口程序中添加@EnableFeignClients 注解
@SpringBootApplication
@EnableFeignClients
public class Demo2Application {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  • 添加FeignClient客户端
@FeignClient(name="helloWorld", url="http://localhost:8080")
public interface HelloWorldClient {

    @GetMapping("/test2")
    String test(@RequestParam("p1") String p1, @RequestParam("p2") String p2);
}
  • 进行单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {

    @Autowired
    HelloWorldClient helloWorldClient;

    @Test
    public void contextLoads() {
        System.out.println(helloWorldClient.test("123","123"));
    }
}
  • 以上就是整个构建Feign客户端请求的Http接口的示例,是不是用起来比HttpClient方便很多呢,SpringCloud在实际应用中并非如此使用Feign客户端,但是也是基于这样的一个基本原理,SpringCloud在实际应用中的使用方式不着急介绍,在最后我会串起来讲

    参考资料

  • Feign基础入门及特性讲解

SpringCloud-Feign第一课-使用示例

标签:param   原理   href   基本   很多   wired   res   功能   一课   

原文地址:https://www.cnblogs.com/accessking/p/11111699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!