在Spring Cloud集群中,各个角色的通信基于REST服务,在调用服务时,需要使用REST客户端,常用,除了使用Spring自带的RestTemplate,也可使用另一个REST客户端:Feign。

使用Feign时,可以使用自带注解或第三方注解来修饰接口,使得接口具有访问Web Service的能力。
Feign还支持插件式的编码器和解码器,对请求和响应进行不同的封装和解析。
Spring Cloud将Feign集成到Netflix项目中,与Eureka、Ribbon集成时,Feign就具有负载均衡的功能。
Feign在Spring Boot Web项目的使用例子可参考:《Spring Boot 2 发布与调用REST服务

下面例子为在Spring Cloud的使用。
开发工具:IntelliJ IDEA 2019.2.3

一、服务器端

1、创建项目

IDEA中创建一个新的SpringBoot项目,名称为“spring-feign-server”,SpringBoot版本选择2.1.10,在选择Dependencies(依赖)的界面勾选Spring Cloud Discovery ->
Eureka Server,创建完成后的pom.xml配置文件自动添加SpringCloud最新稳定版本依赖,当前为Greenwich.SR3。
pom.xml完整内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-feign-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-feign-server</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

2、修改配置application.yml

修改端口号为8761;取消将自己信息注册到Eureka服务器,不从Eureka服务器抓取注册信息。

server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false

3、修改启动类代码SpringFeignServerApplication.java

增加注解@EnableEurekaServer

package com.example.springfeignserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication
@EnableEurekaServer
public class SpringFeignServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringFeignServerApplication.class, args);
}
}

二、服务提供者

1、创建项目

IDEA中创建一个新的SpringBoot项目,除了名称为“spring-feign-provider”,其它步骤和上面创建服务器端一样。

2、修改配置application.yml

spring:
application:
name: spring-feign-provider
eureka:
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

3、添加一个实体类User.java

package com.example.springfeignprovider;

public class User {
String name;
Integer age; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}

4、修改启动类代码SpringFeignProviderApplication.java

增加注解@EnableEurekaClient和@RestController;
让类在启动时读取控制台输入,决定使用哪个端口启动服务器;
增加2个测试用的控制器方法。

package com.example.springfeignprovider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import java.util.Scanner; @SpringBootApplication
@EnableEurekaClient
@RestController
public class SpringFeignProviderApplication { public static void main(String[] args) {
//SpringApplication.run(SpringFeignProviderApplication.class, args);
Scanner scan = new Scanner(System.in);
String port = scan.nextLine();
new SpringApplicationBuilder(SpringFeignProviderApplication.class).properties("server.port=" + port).run(args);
} @RequestMapping("/hello")
public String hello(HttpServletRequest request) {
return "hello world." + request.getServerPort();
} @RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user(@PathVariable String name) {
User u = new User();
u.setName(name);
u.setAge(30);
return u;
}
}

三、服务调用者

1、创建项目
IDEA中创建一个新的SpringBoot项目,名称为“spring-feign-invoker”,SpringBoot版本选择2.1.10,在选择Dependencies(依赖)的界面勾选Spring Cloud Discovery -> Eureka Server,Spring Cloud Routing -> OpenFeign。
pom.xml完整内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-feign-invoker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-feign-invoker</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency> <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

2、修改配置application.yml

server:
port: 9000
spring:
application:
name: spring-feign-invoker
eureka:
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

3、添加一个实体类User.java

package com.example.springfeigninvoker;

public class User {
String name;
Integer age; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}

4、添加一个客户端接口UserClient.java

package com.example.springfeigninvoker;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; //声明调用的服务名称
@FeignClient("spring-feign-provider")
public interface UserClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
String hello(); @RequestMapping(method = RequestMethod.GET, value = "/user/{name}")
User getUser(@PathVariable("name") String name);
}

5、修改启动类代码CloudInvokerApplication.java

增加注解@EnableEurekaClient和@EnableFeignClients。

package com.example.springfeigninvoker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class SpringFeignInvokerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringFeignInvokerApplication.class, args);
}
}

6、添加控制器 InvokerController.java

package com.example.springfeigninvoker;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; @RestController
@Configuration
public class InvokerController {
@Autowired
private UserClient userClient; @RequestMapping(value = "/invokeHello", method = RequestMethod.GET)
public String invokeHello(){
return userClient.hello();
} @RequestMapping(value = "/invokeUser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String invokeUser(){
return userClient.getUser("小明").getAge().toString();
}
}

四、测试

1、启动服务器端。
浏览器访问http://localhost:8761/,正常
2、启动两个服务提供者,在控制台中分别输入8080和8081启动。
(1)浏览器访问 http://localhost:8080/user/小明
输出:{"name":"小明","age":30}
(2)浏览器访问 http://localhost:8081/user/小强
输出:{"name":"小强","age":30}
3、启动服务调用者。
(1)浏览器访问http://localhost:9000/invokeHello,页面显示在下面8080和8081端口之间切换:
hello world.8080
hello world.8081
(2)浏览器访问http://localhost:9000/invokeUser,输出:
30

SpringCloud之Feign:REST客户端的更多相关文章

  1. SpringCloud使用Feign调用其他客户端带参数的接口,传入参数为null或报错status 405 reading IndexService#del(Integer);

    SpringCloud使用Feign调用其他客户端带参数的接口,传入参数为null或报错status 405 reading IndexService#del(Integer); 第一种方法: 如果你 ...

  2. SpringCloud的EurekaClient : 客户端应用访问注册的微服务(有断路器场景)

    演示客户端应用如何访问注册在EurekaServer里的微服务 一.概念和定义 采用Ribbon或Feign方式访问注册到EurekaServer中的微服务.1.Ribbon实现了客户端负载均衡,2. ...

  3. SpringCloud(5)---Feign服务调用

    SpringCloud(5)---Feign服务调用 上一篇写了通过Ribbon进行服务调用,这篇其它都一样,唯一不一样的就是通过Feign进行服务调用. 注册中心和商品微服务不变,和上篇博客一样,具 ...

  4. springcloud 实战 feign使用中遇到的相关问题

    springcloud 实战 feign使用中遇到的相关问题 1.使用feign客户端调用其他微服务时,session没有传递成功,sessionId不一样. /** * @author xbchen ...

  5. SpringCloud之Feign负载均衡(四)

    整合Feign pom.xml <dependency> <groupId>org.springframework.cloud</groupId> <arti ...

  6. SpringCloud+Eureka+Feign+Ribbon的简化搭建流程,加入熔断,网关和Redis缓存[2]

    目录 前提:本篇是基于 SpringCloud+Eureka+Feign+Ribbon的简化搭建流程和CRUD练习[1] 的修改与拓展 1.修改consumer的CenterFeign.java,把返 ...

  7. SpringCloud的EurekaClient : 客户端应用访问注册的微服务(无断路器场景)

    演示客户端应用如何访问注册在EurekaServer里的微服务 一.概念和定义 采用Ribbon或Feign方式访问注册到EurekaServer中的微服务.1.Ribbon实现了客户端负载均衡,2. ...

  8. SpringCloud 在Feign上使用Hystrix(断路由)

    SpringCloud  在Feign上使用Hystrix(断路由) 第一步:由于Feign的起步依赖中已经引入了Hystrix的依赖,所以只需要开启Hystrix的功能,在properties文件中 ...

  9. springcloud 之 feign的重复性调用 优化

    最近有一个springcloud的feign请求,用于获取坐标经纬度的信息,返回结果永远是固定不变的,所以考虑优化一下,不然每次转换几个坐标都要去请求feign,返回的所有坐标信息,数据量太大导致耗时 ...

  10. 解决SpringCloud使用Feign跨服调用时header请求头中的信息丢失

    在使用SpringCloud进行Feign跨服调用时header请求头中的信息会丢失,是因为Feign是不会带上当前请求的Cookie信息和头信息的,这个时候就需要重写请求拦截. 1.需要重写Requ ...

随机推荐

  1. 洛谷 题解 2165 [AHOI2009]飞行棋

    本蒟蒻又来发题解了, 看到这个题目,本蒟蒻直接开始推公式.. 嗯,可以通过弧长,推出弦长(l = 2 * r * cos(90 * l / (r * Π)); 然后对比各条弦长的平方和与直径的平方. ...

  2. luogu P4343 [SHOI2015]自动刷题机 |二分答案

    题目描述 曾经发明了信号增幅仪的发明家 SHTSC 又公开了他的新发明:自动刷题机--一种可以自动 AC 题目的神秘装置. 自动刷题机刷题的方式非常简单:首先会瞬间得出题目的正确做法,然后开始写程序. ...

  3. Unity3D for iOS初级教程:Part 1/3(下)

    转自:http://www.cnblogs.com/alongu3d/archive/2013/06/01/3111735.html 一个手指来统治他们 但是等等,你还没有完全完成! 如果你玩游戏有一 ...

  4. [TimLinux] JavaScript 元素动态显示

    1. css的opacity属性 这个属性用于:设置元素的不透明级别,取值范围:从 0.0 (完全透明)到 1.0(完全不透明),元素所在的文本流还在.这个属性的动态变化可以用来设置元素的淡入淡出效果 ...

  5. AtCoder-3856

    An adult game master and N children are playing a game on an ice rink. The game consists of K rounds ...

  6. Python入门(一个有趣的画图例子实战)你肯定不会

    前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:qiu_fang  画一条可爱的python(蟒蛇): import t ...

  7. F#周报2019年第50期

    新闻 Azure Functions 3.0系统上线 GC性能架构--第1部分 ConfigureAwait问题解答 介绍System.Threading.Channels Windows Serve ...

  8. JavaScript中的"奇奇怪怪"

    filter等方法的隐式转化 var list = [1,,2,,0,5,9];console.log(list[1]); // console: undefinedconsole.log(list[ ...

  9. IDEA 支持scala开发

    IDEA支持scala开发,需要安装scala插件,并且pom.xml也需要添加对应依赖. 1. 安装scala插件 下载地址:https://plugins.jetbrains.com/plugin ...

  10. Java堆的结构是什么样子的?什么是堆中的永久代(Perm Gen space)?

    JVM的堆是运行时数据区,所有类的实例和数组都是在堆上分配内存.它在JVM启动的时候被创建.对象所占的堆内存是由自动内存管理系统也就是垃圾收集器回收. 堆内存是由存活和死亡的对象组成的.存活的对象是应 ...