五:Spring Cloud 之服务发现与调用-Feign

本文介绍了Feign在Spring Cloud中作为声明式服务调用客户端的使用,包括创建接口并注解、配置Eureka、设置负载均衡,并通过实际代码示例展示了如何启动和验证服务调用的过程。
摘要由CSDN通过智能技术生成

1. 简介

Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.

  • Feign 是一个声明式调用HTTP协议服务的客户端
  • 支持注解形式发现与调用服务
  • 支持编码与解码
  • 与Ribbon、Eureka结合使用可实现负载均衡功能

2. 代码实现

2.1涉及的模块

  • eureka-server-singleton:服务注册中心,端口8761
  • eureka-service: 服务提供者,通过profile指定不同端口模拟一组微服务,端口8762、8763
  • eureka-service-feign:通过Feign调用服务提供者提供的服务

2.2 源代码

2.2.1 Github地址

https://github.com/andyChenHuaYing/spring-cloud-demo

2.2.2 切换

通过tag切换git tag -d v1.0,若想修改,可根据此tag创建新的分支。

2.3 eureka-server-singleton

Spring Cloud 之服务发现与调用-Ribbon#2.3 eureka-server-singleton 没有任何区别

2.4 eureka-service

Spring Cloud 之服务发现与调用-Ribbon#2.4 eureka-service 没有任何区别

2.5 eureka-service-feign

2.5.1整体实现步骤

  1. pom.xml中引入spring-cloud-starter-netflix-eureka-serverspring-cloud-starter-openfeign依赖
  2. application.yml中指定配置项,端口、application.name、eureka-server地址
  3. SpringBoot 启动类添加启用Fegin的注解@EnableFeignClients
  4. 在当前项目Service接口类名上使用FeignClient注解指定服务提供者的服务名@FeignClient("eureka-service")
  5. 在需要调用服务提供者的接口方法之上使用注解指定调用服务提供者提供的方法@RequestMapping("/print")
  6. 在需要使用服务提供者提供的方法之处,使用第4步与第5步实例化好的服务提供者的方法

2.5.2 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-finchley-demo</artifactId>
        <groupId>org.oscar.scd</g
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值