在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. Linux下RocketMQ下载安装教程

    一.下载 1.官网下载:下载地址   2.百度网盘下载:下载地址 提取码:0g5a java开发工具下载地址及安装教程大全,点这里. 更多深度技术文章,在这里. 二.安装及启动 1.将zip文件上传到 ...

  2. 开通博客第一天,记录此时此刻,开始学习加强c#

    从2017年6月毕业到现在,不断的学习.net,在工作中不断的加强技术,终于在此时此刻决定开通博客,记录此后每一天学习的技术点,两年来,每天所涉及的技术点很杂,学了这个忘了那个,总感觉在进步却总是觉得 ...

  3. html小工具——文章注释编辑器

    在网上阅读文章时,读者时常会想针对某段文字写一些自己的感想,可惜大部分阅读网站并不提供这样的功能,读者往往只能将文本复制到本地或在线的编辑器中编辑注释,之后如果想在其他地方回顾这些注释也必须先本地安装 ...

  4. 【TCP/IP网络编程】:04基于TCP的服务器端/客户端

    摘要:结合前面所讲述的知识,本篇文章主要介绍了简单服务器端和客户端实现的框架流程及相关函数接口. 理解TCP和UDP 根据数据传输方式的不同,基于网络协议的套接字一般分为TCP套接字和UDP套接字(本 ...

  5. 【玩转SpringBoot】看似复杂的Environment其实很简单

    喜欢写代码,讨厌配环境 我相信这十个字的小标题代表了大多数码农的心声. 十年前读大学时,学校开设了C语言还有C++.但是学习这两种语言,对于新手来说非常没有成就感. 于是我就在校门口买个光盘,装个VS ...

  6. 《Java基础知识》Java静态内部类、匿名内部类、成员式内部类和局部内部类

    内部类可以是静态(static)的,可以使用 public.protected 和 private 访问控制符,而外部类只能使用 public,或者默认. 成员式内部类 在外部类内部直接定义(不在方法 ...

  7. JavaFX如何制作鼠标多击事件?

    JavaFX制作鼠标双击或者多击事件需要用到getClickCount()方法,这个方法需要添加addEventHandler()方法,addEventHandler()是事件方法. 1 scene. ...

  8. BOM对象——History

    BOM对象--History <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  9. JS---DOM---part4 课程介绍 & part3 复习

    part4 课程介绍 事件 1. 绑定事件的区别 2. 移除绑定事件的方式及区别和兼容代码 3. 事件的三个阶段 4. 事件冒泡 5. 为同一个元素绑定多个不同的事件,指向的是同一个事件处理函数 6. ...

  10. sqoop 安装与使用

    Sqoop(发音:skup)是一款开源的工具,主要用于在Hadoop(Hive)与传统的数据库间进行数据的传递,可以将一个关系型数据库(例如 : MySQL ,Oracle ,Postgres等)中的 ...