基于上一篇文章:https://www.cnblogs.com/xuyiqing/p/10867739.html

使用Ribbon实现了订单服务调用商品服务的Demo

下面介绍如何使用Feign实现这个Demo

Feign:伪RPC客户端,底层基于HTTP

在订单服务的POM中加入依赖

        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

并在启动类中加入注解,这里已经加入的Ribbon可以保留

package org.dreamtech.orderservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate; @SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication { public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
} @Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

Feign接口

package org.dreamtech.orderservice.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name = "product-service")
public interface ProductClient {
@RequestMapping("/api/product/find")
String findById(@RequestParam(value = "id")int id);
}

使用

package org.dreamtech.orderservice.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import org.dreamtech.orderservice.domain.ProductOrder;
import org.dreamtech.orderservice.service.ProductClient;
import org.dreamtech.orderservice.service.ProductOrderService;
import org.dreamtech.orderservice.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate; import java.util.Date;
import java.util.Map;
import java.util.UUID; @Service
public class ProductOrderServiceImpl implements ProductOrderService { private final ProductClient productClient; @Autowired
public ProductOrderServiceImpl(ProductClient productClient) {
this.productClient = productClient;
} @Override
public ProductOrder save(int userId, int productId) { String response = productClient.findById(productId);
JsonNode jsonNode = JsonUtils.str2JsonNode(response); ProductOrder productOrder = new ProductOrder();
productOrder.setCreateTime(new Date());
productOrder.setUserId(userId);
productOrder.setTradeNo(UUID.randomUUID().toString()); productOrder.setProductName(jsonNode.get("name").toString());
productOrder.setPrice(Integer.parseInt(jsonNode.get("price").toString())); return productOrder;
}
}

工具类

package org.dreamtech.orderservice.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class JsonUtils { private static final ObjectMapper objectMapper = new ObjectMapper(); public static JsonNode str2JsonNode(String str) {
try {
return objectMapper.readTree(str);
} catch (IOException e) {
return null;
}
}
}

重启Eureka Server和多个product-service:

访问http://localhost:8781/api/order/save?user_id=1&product_id=1,成功

使用注意:

1.Feign的路由和服务的路由必须一致(如这里的/api/product/find)

2.注意服务名的一致

3.参数必须加入@RequestParam确保参数名和服务的一致

4.如果服务的参数加入了@RequestBody,Feign客户端也要加入@RequestBody并修改为POST方式

5.这里获取到JSON直接解析,实际情况可以抽取公共实体类为JAR包引入返回实体类

FeignClient原理:

查看Clien类可以发现,Feign的实现是通过HTTP形式:

        HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
HttpURLConnection connection = (HttpURLConnection)(new URL(request.url())).openConnection();
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection sslCon = (HttpsURLConnection)connection;
if (this.sslContextFactory != null) {
sslCon.setSSLSocketFactory(this.sslContextFactory);
} if (this.hostnameVerifier != null) {
sslCon.setHostnameVerifier(this.hostnameVerifier);
}
}

Client的实现类中:

发现Feign调用了Ribbon做负载均衡

    public Response execute(Request request, Options options) throws IOException {
try {
URI asUri = URI.create(request.url());
String clientName = asUri.getHost();
URI uriWithoutHost = cleanUrl(request.url(), clientName);
RibbonRequest ribbonRequest = new RibbonRequest(this.delegate, request, uriWithoutHost);
IClientConfig requestConfig = this.getClientConfig(options, clientName);
return ((RibbonResponse)this.lbClient(clientName).executeWithLoadBalancer(ribbonRequest, requestConfig)).toResponse();
} catch (ClientException var8) {
IOException io = this.findIOException(var8);
if (io != null) {
throw io;
} else {
throw new RuntimeException(var8);
}
}
}

处理超时问题:实际情况服务和调用者之间的通信可能较慢,这时候Feign会报错

如下配置Feign超时实际为10秒

feign:
client:
config:
default:
connectTimeout: 10000
readTimeout: 10000

Feign默认超时为1秒

Feign和Ribbon的对比:

1.Feign里面包含Ribbon,Feign的负载均衡由Ribbon实现

2.Feign更方便,可以和Hystrix结合

Spring Cloud(4):Feign的使用的更多相关文章

  1. spring cloud 使用feign 遇到问题

    spring cloud 使用feign 项目的搭建 在这里就不写了,本文主要讲解在使用过程中遇到的问题以及解决办法 1:示例 @RequestMapping(value = "/gener ...

  2. spring cloud(四) feign

    spring cloud 使用feign进行服务间调用 1. 新建boot工程 pom引入依赖 <dependency> <groupId>org.springframewor ...

  3. spring cloud关于feign client的调用对象列表参数、设置header参数、多环境动态参数试配

    spring cloud关于feign client的调用 1.有些场景接口参数需要传对象列表参数 2.有些场景接口设置设置权限等约定header参数 3.有些场景虽然用的是feign调用,但并不会走 ...

  4. Spring Cloud 整合 Feign 的原理

    前言 在 上篇 介绍了 Feign 的核心实现原理,在文末也提到了会再介绍其和 Spring Cloud 的整合原理,Spring 具有很强的扩展性,会把一些常用的解决方案通过 starter 的方式 ...

  5. Spring Cloud 之 Feign

    新建Spring Boot工程,命名为feign 1.pom.xml添加依赖 <?xml version="1.0" encoding="UTF-8"?& ...

  6. Spring Cloud中Feign如何统一设置验证token

    代码地址:https://github.com/hbbliyong/springcloud.git 原理是通过每个微服务请求之前都从认证服务获取认证之后的token,然后将token放入到请求头中带过 ...

  7. Spring Cloud 组件 —— feign

    feign 作为一个声明式的 Http Client 开源项目.在微服务领域,相比于传统的 apache httpclient 与在 spring 中较为活跃的 RestTemplate 更面向服务化 ...

  8. spring cloud中feign的使用

    我们在进行微服务项目的开发的时候,经常会遇到一个问题,比如A服务是一个针对用户的服务,里面有用户的增删改查的接口和方法,而现在我有一个针对产品的服务B服务中有一个查找用户的需求,这个时候我们可以在B服 ...

  9. spring cloud 之 Feign 使用HTTP请求远程服务

    一.Feign 简介 在spring Cloud Netflix栈中,各个微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端.我们可以使用JDK原生的URLCo ...

  10. spring cloud 之 Feign的使用

    1.添加依赖 2.创建FeignClient 原理:Spring Cloud应用在启动时,Feign会扫描标有@FeignClient注解的接口,生成代理,并注册到Spring容器中.生成代理时Fei ...

随机推荐

  1. 【BZOJ4059】Non-boring sequences(分析时间复杂度)

    题目: BZOJ4059 分析: 想了半天没什么想法,百度到一个神仙做法-- 设原数列为 \(a\),对于每一个 \(i\) 求出前一个和后一个和 \(a_i\) 相等的位置 \(pre[i]\) 和 ...

  2. FJOI2019退役记

    day1 不意外地一点都不紧张,早就感觉没有机会了吧 进场非常从容地读完了三道题,开始写t1暴力,接着就开始自闭,不知道该开t2还是t3,最后先开了t3,想了想这不是选两条不相交的链吗,这个暴力不是林 ...

  3. web项目无法部署到eclipse配置的本地tomcat

    一.发现问题 在eclipse中新建Dynamic Web Project,配置好本地的tomcat并写好代码后选择Run on Server,但运行后发现在tomcat的安装目录下的webapps并 ...

  4. Spring框架及AOP

    Spring核心概念 Spring框架大约由20个功能模块组成,这些模块主分为六个部分: Core Container :基础部分,提供了IoC特性. Data Access/Integration ...

  5. Git——github高级

    分支管理 分支不是越多越好,只求一个稳定的分支,即master不要轻易去更改 对应master要有一个开发者分支,保证mater分支的稳定性 所有的功能都在开发者分支上进行 在所有功能开发后新建发布分 ...

  6. Farseer.net轻量级开源框架 入门篇:查询数据详解

    导航 目   录:Farseer.net轻量级开源框架 目录 上一篇:Farseer.net轻量级开源框架 入门篇: 删除数据详解 下一篇:Farseer.net轻量级开源框架 中级篇: Where条 ...

  7. VC++函数只被调用一次

    如何保证某个函数只被调用一次   一个函数caller会在其内部调用另外一个函数callee,现在的情况是,caller可能会在多个地方被多次调用,而你希望callee只在第一次被调用时被调用一次.一 ...

  8. 基于C++的多态性动态判断函数

    这里先有一个问题: 问题描述:函数int getVertexCount(Shape * b)计算b的顶点数目,若b指向Shape类型,返回值为0:若b指向Triangle类型,返回值为3:若b指向Re ...

  9. 已集成 VirtIO驱动windows server 2012, 2008, 2003的ISO镜像下载

    已集成 VirtIO驱动简体中文windows server 2012, 2008, 2003系统ISO镜像下载地址. 适用于上传自定义ISO并且使用 VirtIO驱动的kvm架构vps,vultr家 ...

  10. linux vim 常用操作

    vim 字符级 上k下j左h右i,键盘的方向键也可以移动 单词级 b上个单词首字母 w下个单词首字母 e下个单词的尾字母 行级 0行首 $行尾 删除 dd 删除光标所在行 文档级 gg 文档首行,首个 ...