SpringCloud之Feign:REST客户端
在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客户端的更多相关文章
- SpringCloud使用Feign调用其他客户端带参数的接口,传入参数为null或报错status 405 reading IndexService#del(Integer);
SpringCloud使用Feign调用其他客户端带参数的接口,传入参数为null或报错status 405 reading IndexService#del(Integer); 第一种方法: 如果你 ...
- SpringCloud的EurekaClient : 客户端应用访问注册的微服务(有断路器场景)
演示客户端应用如何访问注册在EurekaServer里的微服务 一.概念和定义 采用Ribbon或Feign方式访问注册到EurekaServer中的微服务.1.Ribbon实现了客户端负载均衡,2. ...
- SpringCloud(5)---Feign服务调用
SpringCloud(5)---Feign服务调用 上一篇写了通过Ribbon进行服务调用,这篇其它都一样,唯一不一样的就是通过Feign进行服务调用. 注册中心和商品微服务不变,和上篇博客一样,具 ...
- springcloud 实战 feign使用中遇到的相关问题
springcloud 实战 feign使用中遇到的相关问题 1.使用feign客户端调用其他微服务时,session没有传递成功,sessionId不一样. /** * @author xbchen ...
- SpringCloud之Feign负载均衡(四)
整合Feign pom.xml <dependency> <groupId>org.springframework.cloud</groupId> <arti ...
- SpringCloud+Eureka+Feign+Ribbon的简化搭建流程,加入熔断,网关和Redis缓存[2]
目录 前提:本篇是基于 SpringCloud+Eureka+Feign+Ribbon的简化搭建流程和CRUD练习[1] 的修改与拓展 1.修改consumer的CenterFeign.java,把返 ...
- SpringCloud的EurekaClient : 客户端应用访问注册的微服务(无断路器场景)
演示客户端应用如何访问注册在EurekaServer里的微服务 一.概念和定义 采用Ribbon或Feign方式访问注册到EurekaServer中的微服务.1.Ribbon实现了客户端负载均衡,2. ...
- SpringCloud 在Feign上使用Hystrix(断路由)
SpringCloud 在Feign上使用Hystrix(断路由) 第一步:由于Feign的起步依赖中已经引入了Hystrix的依赖,所以只需要开启Hystrix的功能,在properties文件中 ...
- springcloud 之 feign的重复性调用 优化
最近有一个springcloud的feign请求,用于获取坐标经纬度的信息,返回结果永远是固定不变的,所以考虑优化一下,不然每次转换几个坐标都要去请求feign,返回的所有坐标信息,数据量太大导致耗时 ...
- 解决SpringCloud使用Feign跨服调用时header请求头中的信息丢失
在使用SpringCloud进行Feign跨服调用时header请求头中的信息会丢失,是因为Feign是不会带上当前请求的Cookie信息和头信息的,这个时候就需要重写请求拦截. 1.需要重写Requ ...
随机推荐
- luogu P3805 【模板】manacher算法
题目描述 给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度. 字符串长度为n 输入格式 一行小写英文字符a,b,c...y,z组成的字符串S 输出格式 一个整数表示 ...
- 使用SQL计算宝宝每次吃奶的时间间隔
需求:媳妇儿最近担心宝宝的吃奶时间不够规律,网上说是正常平均3小时喂奶一次,让我记录下每次的吃奶时间,分析下实际是否偏差很大,好在下次去医院复查时反馈给医生. 此外,还要注意有时候哭闹要吃奶,而实际只 ...
- APP 框架搭建
在开发一款app前必须先把框架搭建好,这样能避免代码混乱,多人开发时遇到bug难以解决. 构建MVC整体框架的缺点是会导致VC代码量过大,也存在一些不足.借鉴了网上牛人的思路后,https://www ...
- idea 上传svn忽略文件
在idea最下面找到Version Control 默认我们svn提交的文件都在Default ChangeList中 我们创建一个新的ChangeList
- JavaWeb中的MVC 下
代码较多,请先略过代码,看懂逻辑在研究代码 引入 回顾上一节中的项目,最终的层次结构: 在MVC上中,我们分析了MVC设计模式具备的优点,以及不足,并在其基础上增了Service层用于处理业务逻辑,但 ...
- python之with语句结合上下文管理器
所谓上下文管理器即在一个类中重写了__enter__方法和__exit__方法的类就可以成为上下文管理器类. 我们可以通过with语句结合上下文管理器简化一些操作. 使用with语句结合自定义上下文管 ...
- Elasticsearch 监控指标解析
1.集群监控 集群监控主要包括两个方面的内容,分别是集群健康情况和集群的运行状态. 集群健康状态可以通过以下api获取: http://ip:9200/_cluster/health?pretty 关 ...
- 记录一次Windows简单构建Dockerfile
参考文档[https://www.cnblogs.com/GraceSkyer/p/9908984.html] 1]环境说明 操作系统 :win10 ,docker软件:Docker for Win ...
- 在WPF中开启摄像头扫描二维码(Media+Zxing)
近两天项目中需要添加一个功能,是根据摄像头来读取二维码信息,然后根据读出来的信息来和数据库中进行对比显示数据. 选择技术Zxing.WPFMediaKit.基本的原理就是让WPFmediaKit来对摄 ...
- 阿里云服务器部署Tornado应用
本篇详细介绍tornado应用部署到阿里云服务器上的全过程. Tornado程序地址:github https://github.com/ddong8/ihasy.git 准备工作:阿里云服务器Cen ...