【Spring Cloud】分布式必学springcloud(七)——声明式服务调用Feign

一、前言

      在上篇博客中,小编带大家接触了断路器Hystrix,是不是很好玩。分布式服务之间有了Hystrix,可以很好的提高容错性能。

      但是在实际开发中,项目中会有很多的服务间的调用,对于服务的调用不可能是一处。所以我们针对各个服务自行封装一些客户端类来包装这些依赖服务的调用。

      SpringCloud Feign就在这个基础上做了封装,他可以帮助我们定义接口。开发时候只需要定义接口并添加相应的注解,大大的简化了使用ribbon的开发量。

这里写图片描述

这里写图片描述

二、准备

2.1 准备

      根据上一篇博客搭建好的框架,我们在这个基础上进行修改,您可以在这里得到代码。

      https://github.com/AresKingCarry/SpringCloudDemo

2.2 建立feign项目

      创建springboot项目。

这里写图片描述

2.3 添加Feign的依赖

      在pom文件中添加feign的依赖spring-cloud-starter-feignspring-cloud-starter-eureka

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

2.4 启动类添加启动feign

      在启动类添加@EnableFeignClients来开启对Spring Cloud Feign的支持:

package com.wl.feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class FeignApplication {

	public static void main(String[] args) {
		SpringApplication.run(FeignApplication.class, args);
	}
}

3.5 service

      定义ClientService 接口,通过@FeignClient(value = "xxxxxxx")指定服务名来绑定服务,然后通过springmvc注解来绑定具体提供服务的rest接口。

      这里注意的是,绑定的服务名,不区分大小写。所以client1和CLIENT1都是可以的。

package com.wl.feign.service;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by Ares on 2018/4/23.
 */
@FeignClient(value = "client1")
public interface ClientService {

    @GetMapping("/user/findById")
    String findById(@RequestParam("id")String id);
}

2.6 Controller

package com.wl.feign.controller;

import com.wl.feign.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Ares on 2018/4/23.
 */
@RestController
public class ClientController {

    @Autowired
    ClientService clientService;

    @GetMapping("/user/findById")
    public String findById(@RequestParam("id")String id){
       return clientService.findById(id);
    }
}

2.7 配置文件

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 7001
spring:
  application:
    name: feign-service

2.8 测试验证

      因为feign是对ribbon的封装,所以默认的负载均衡策略依旧为轮询。依次启动Eureka、两个服务提供者、feign。

      访问http://ares-pc:7001//user/findById?id=wl

![这里写图片描述](https://img-blog.csdn.net/20180423100012738?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2tpc3NjYXRmb3JldmVy/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)

三、添加断路器

      在上篇博客中,我们在Ribbon中使用了Hystrix断路器,同样,我们也可以在Feign中使用断路器。

这里写图片描述

3.1 开启断路器

      因为Feign是对springcloud Ribbon和springcloud Hystrix的封装,所以Feign是带短路器 的,需要我们在配置文件中,开启短路器。

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 7001
spring:
  application:
    name: feign-service

feign:
  hystrix:
    enabled: true

3.2 建立Service接口的实现类

      定义ClientFallback 实现类,并注入spring容器。

package com.wl.feign.exception;

import com.wl.feign.service.ClientService;
import org.springframework.stereotype.Component;

/**
 * Created by Ares on 2018/4/23.
 */
@Component
public class ClientFallback implements ClientService {
    @Override
    public String findById(String id) {
        return "调用Client1服务超时,调用方法findById(id)-根据id查询所有记录"+id;
    }
}

3.3 修改service

      添加fallback,指明如果出错后要调用的类。

package com.wl.feign.service;

import com.wl.feign.exception.ClientFallback;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by Ares on 2018/4/23.
 */
@FeignClient(value = "client1",fallback = ClientFallback.class)
public interface ClientService {

    @GetMapping("/user/findById")
    String findById(@RequestParam("id")String id);
}

3.4 测试

      依次启动eureka、两个提供者、feign,正常启动的情况下:

这里写图片描述

      当关闭一个提供者后,情况如下:

这里写图片描述

四、小结

      通过feign,是不是感觉有点面向对象的感觉,把一些乱的调用,整理了一下。很好的操作。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
# fat FAT ,基于springboot , 使用zookeeper,redis , spring async , spring transactionManager的强一致性分布式事务解决方案 ## 框架介绍 纯编码方,强一致性。<br> 使用redis/zookeeper作为注册中心 ,代理事务的执行,使用spring async异步处理事务线程。<br> 基于注解使用,对业务代码可以说是零入侵,目前内置适配spring-cloud(Feign调用) , dubbo。<br> 同时具备一定的扩展性与兼容性,因为存在自定义的服务框架,或者以后会涌现出更多的流行分布式服务框架,所以会提供一些组件适配自定义服务框架。 ## Maven依赖 ```java <dependency> <groupId>com.github.cjyican</groupId> <artifactId>fat-common</artifactId> <version>1.0.6-RELEASE</version> </dependency> ``` ## 使用示例 ### step0:SpringBootApplication加上@EnableFat注解 ```java @SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient @EnableFeignClients @EnableFat public class FatboyEurekaRibbonApplication { public static void main(String[] args) { SpringApplication.run(FatboyEurekaRibbonApplication.class, args); } } ``` ### step1:配置注册中心 使用redis/zookeeper作为注册中心,优先使用zookeeper。为隔离业务使用的redis和注册中心的redis,提供了一套属性配置。 在业务redis/zookeeper作为注册中心与注册中心相同时,也需要配置。 请保证各个服务的注册中心配置一致,否则无法协调分布式事务。 ```java #Fat # Redis数据库索引(默认为0) fat.redis.database=0 # Redis服务器地址 fat.redis.host= # Redis服务器连接端口 fat.redis.port=6379 # Redis服务器连接密码(默认为空) fat.redis.password= # 连接池最大连接数(使用负值表示没有限制) fat.redis.pool.max-active=20 # 连接池最大阻塞等待时间(使用负值表示没有限制) fat.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 fat.redis.pool.max-idle=10 # 连接池中的最小空闲连接 fat.redis.pool.min-idle=2 # 连接超时时间(毫秒) fat.redis.timeout=1000 # 集群模,如有配置,将优先使用集群 fat.redis.cluster.nodes=x.x.x.x:x,x.x.x.x:x # zookeeper服务器地址 fat.zookeeper.host=x.x.x.x:x,x.x.x.x:x # zookeeper活跃时间 fat.zookeeper.sessionTimeout=x.x.x.x:x,x.x.x.x:x ``` 应用标识,与spirng.application.name一致,必须配置 ```java spring.application.name=fatboy-eureka-ribbon ``` ### step2:服务入口方法加入注解@FatServiceRegister注册 在需要开启分布式事务管理的入口方法中加入注解@FatServiceRegister,注意不要重复添加。dubbo的直接加在serviceImpl.method上面就可以 ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你个佬六

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值