在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. 洛谷 P2388 阶乘之乘 题解

    本蒟蒻又来发题解了QwQ; 看到这个题目,本蒟蒻第一眼就想写打个暴力: 嗯,坏习惯: 但是,动动脑子想一想就知道,普通的的暴力是过不了的: 但是,身为蒟蒻的我,也想不出什么高级的数学方法来优化: 好, ...

  2. universal link使用

    iOS9之后,苹果推出了universal link方案,该方案较url scheme有明显的改善.url scheme很难做到唯一. 而 universal link却是你自己控制的. 1.有一个H ...

  3. A.Changing Volume

    题目:改变音量 题意:给定两个数a和b,有6个操作(-5, -2, -1, +1, +2, +5),求a变到b的最小操作次数 操作的过程中不能变到小于0,即音量不能调到小于0 分析: (贪心),我们可 ...

  4. 这十道经典Python笔试题,全做对算我输

    经常有小伙伴学了Python不知道是否能去找工作,可以来看下这十道题检验你的成果: 1.常用的字符串格式化方法有哪些?并说明他们的区别 a. 使用%,语法糖 print("我叫%s,今年%d ...

  5. 使用iCamera 测试MT9F002 1400w高分辨率摄像头说明 续集2

    使用iCamera 测试MT9F002 1400w高分辨率摄像头说明 续集2 本方案测试三种分辨率输出(其他更多分辨率设置,可以参考手册配置) 3776*3288=1241万像素 3776*2832= ...

  6. Redis第二讲【Redis基本命令和五大数据结构】

    [二.Redis基本命令和五大数据结构] redis的基础知识和命令 redis 是一个单进程(包装epoll函数来对读写事件进行相应) 默认有16个数据库,初始使用的数据库为0号库 默认端口为637 ...

  7. Android中实现异步轮询上传文件

    前言 前段时间要求项目中需要实现一个刷卡考勤的功能,因为涉及到上传图片文件,为加快考勤的速度,封装了一个异步轮询上传文件的帮助类 效果  先上效果图 设计思路 数据库使用的框架是GreenDao,一个 ...

  8. 修改element-ui默认属性

    修改element ui默认的样式 如果要组件内全局修改 首先在浏览器里F12找到element默认的UI类名 找到要修改的默认类名以后 在文件中修改代码,重写属性 <style> .el ...

  9. 你不会还在用这8个错误的SQL写法吧?

    1.LIMIT 语句 分页查询是最常用的场景之一,但也通常也是最容易出问题的地方.比如对于下面简单的语句,一般 DBA 想到的办法是在 type, name, create_time 字段上加组合索引 ...

  10. [从今天开始修炼数据结构]图的最短路径 —— 迪杰斯特拉算法和弗洛伊德算法的详解与Java实现

    在网图和非网图中,最短路径的含义不同.非网图中边上没有权值,所谓的最短路径,其实就是两顶点之间经过的边数最少的路径:而对于网图来说,最短路径,是指两顶点之间经过的边上权值之和最少的路径,我们称路径上第 ...