第七篇:Feign访问服务集群

一、 什么是  Feign ?

Feign 是一种声明式、模板化的 HTTP 客户端,在 Spring Cloud 中使用 Feign,可以做到使用 HTTP

请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是

个 HTTP 请求。

Feign 的灵感来源于 Retrofit、JAXRS-2.0 和 WebSocket,它使得 Java HTTP 客户端编写更方便,旨在通过最少的资源和代码来实现和 HTTP API 的连接。

 

二:pom依赖
springboot2.0以前的依赖

1

2

3

4

<dependency>

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

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

</dependency>

Finchley.SR1版本 feign的pom依赖

1

2

3

4

<dependency>

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

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

</dependency>

说明:由于很多模块都要用,可以直接在父工程依赖,同时feign无需指定version,因为springclould中已经指定了版本

 

三:@EnableFeignClients启动feign (在调用方启动该注解)

1

2

3

4

5

6

7

8

9

@SpringBootApplication

@EnableEurekaClient

@EnableFeignClients

public class ConsumerApplication {

    public static void main(String[] args) {

        SpringApplication.run(ConsumerApplication.class, args);

    }

 

}

 

四:定义服务接口

1

2

3

4

5

6

7

8

9

10

11

12

13

14

package com.wendao.provider.consumer.feign;

 

import com.wendao.provider.consumer.pojo.User;

import org.springframework.cloud.openfeign.FeignClient;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

//spring-cloud-service-provider为服务提供者的应用名

@FeignClient(name="spring-cloud-service-provider")

public interface IuserBiz {

 

    @RequestMapping(value = "/user/{userId}")

    User findUserById(@PathVariable(name = "userId") Integer uesrId);

 

}

 

这里切记一点:虽然路径中参数名叫userId和方法形参中参数名一致,但是@PathVariable中还是要指定。

 

 

五:调用

1

2

3

4

5

6

7

8

9

10

11

12

13

@RestController

public class ConsumerController {

  

    @Autowired

    private IuserBiz iuserBiz;

  

    @RequestMapping("/findOne/{id}")

    public User findOne(@PathVariable  Integer id){

 

        return iuserBiz.findUserById(id);

    }

  

}

 

小结:服务提供者的代码不用做任何修改,只需要在服务消费者这边修改即可

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值