spring cloud(四):Feign的应用

发布时间:2020-07-05 19:57:51 作者:browser123
来源:网络 阅读:2011

1、概念

  Feign 是一种声明式、模板化的 HTTP 客户端,是一个声明web服务客户端,这便得编写web服务客户端更容易。


2、应用

   2.1 、在项目中,模块与模块之间需要互相调用,比如web模块需要调用service模块的服务,这个时候就需要在web引入Fegin,创建项目web-fegin

   2.2、在pom文件里面添加

        <dependency>

                    <groupId>org.springframework.cloud</groupId>

                    <artifactId>spring-cloud-starter-feign</artifactId>

        </dependency>

  2.3、创建启动类WebFeignApplication

          @SpringBootApplication

            @EnableDiscoveryClient

            @EnableFeignClients(basePackages="com.web")

            public class WebFeignApplication{

                public static void main(String[] args) {

                    SpringApplication.run(FeignApplication.class, args);

                }

            }

2.4、定义服务接口类UserFeignClient

    @FeignClient(name =WebConstants.SERVIE_USER_NAME)

    public interface UserFeignClient {

      @RequestMapping("/{id}")

      public User findByIdFeign(@RequestParam("id") Long id);

    }

 2.5、在web层调用Fegin

        @RestController

        public class FeignController {

          @Autowired

          private UserFeignClient userFeignClient;

          @GetMapping("feign/{id}")

          public User findByIdFeign(@PathVariable Long id) {

            User user = this.userFeignClient.findByIdFeign(id);

            return user;

          }

        }

    
 2.6 如果不使用上面的fegin,则得自己写个服务调用类,来调用service的服务,增加编程的难度,既然有了fegin,就没必要重复造轮子了。


3、application.properties的配置

        spring.application.name=web-fegin

        server.port=8020

        eureka.client.serviceUrl.defaultZone=http://localhost:9411/eureka/

        service.user.name=microservice-provider-user

4、定义常量WebConstants

      public class WebConstants{

             public static final String SERVIE_USER_NAME="${service.user.name}";

           }

5、访问

 http://127.0.0.1:8020/fegin/1


6、总结:

        其实通过Feign封装了HTTP调用服务方法,使得客户端像调用本地方法那样直接调用方法

推荐阅读:
  1. Spring Cloud Alibaba 开发案例之 Nacos 整合 Feign
  2. 如何实现Spring Cloud Zuul路由网关服务过滤

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring cloud fegin

上一篇:如何实现报表设计中的高精度报表套打?

下一篇:仿途牛旅游APP项目开发

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》