SpringCloud微服务之间的通讯,Feign和RestTemplate概念实例详解

SpringCloud微服务之间的通讯,Feign和RestTemplate概念实例详解

技术背景

利用consul注册中心实现了服务的注册和发现功能,那么服务之间是如何调用?在单体应用中,代码可以直接依赖,代码可以直接调用。在微服务架构中,服务都运行在各自的进程中,甚至部署在不同的主机不同的地区,那么需要远程调用技术。

spring cloud 体系中应用比较广泛的服务调用的方式有 2 种

  1. 使用 restTemplate+ribbon 进行服务调用,可以通过ribbon注解RestTemplate模板,使其拥有负载均衡的功能

  2. 使用 feign 进行申明式服务调用,声明之后就像调用本地方法一样 ,feign 默认使用Ribbon 实现负载均衡两种方式都可以实现服务之间的调用,根据情况进行选择。

1. resTemplate介绍

RestTemplateSpring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

简单来说,RestTemplate采用了模版设计的设计模式,将过程中与特定实现相关的部分委托给接口,而这个接口的不同实现定义了接口的不同行为,所以可以很容易的使用不同的第三方http服务,如okHttphttpclient等。

RestTemplate定义了很多的与REST资源交互,一些常用的请求方式的使用。http://www.imooc.com/article/80469

2. Ribbon介绍

Spring Cloud Ribbon是一个基于Http和TCP的客服端负载均衡工具,它是基于Netflix Ribbon实现的。与Eureka或者consul 配合使用时,Ribbon可自动从注册中心获取服务提供者地址列表,并基于负载均衡算法,通过在客户端中配置yml文件NFLoadBalancerRuleClassName来设置服务端列表访问策略。
ribbon中提供的负载均衡的策略

策略名策略声明策略描述实现说明
BestAvailableRulepublic class BestAvailableRule extends ClientConfigEnabledRoundRobinRule选择一个最小的并发请求的server逐个考察Server,如果Server被tripped了,则忽略,在选择其中ActiveRequestsCount最小的server
AvailabilityFilteringRulepublic class AvailabilityFilteringRule extends PredicateBasedRule过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值)使用一个AvailabilityPredicate来包含过滤server的逻辑,其实就就是检查status里记录的各个server的运行状态
WeightedResponseTimeRulepublic class WeightedResponseTimeRule extends RoundRobinRule根据相应时间分配一个weight,相应时间越长,weight越小,被选中的可能性越低。一个后台线程定期的从status里面读取评价响应时间,为每个server计算一个weight。Weight的计算也比较简单responsetime 减去每个server自己平均的responsetime是server的权重。当刚开始运行,没有形成statas时,使用roubine策略选择server。
RetryRulepublic class RetryRule extends AbstractLoadBalancerRule对选定的负载均衡策略机上重试机制。在一个配置时间段内当选择server不成功,则一直尝试使用subRule的方式选择一个可用的server
RoundRobinRulepublic class RoundRobinRule extends AbstractLoadBalancerRuleroundRobin方式轮询选择server轮询index,选择index对应位置的server
RandomRulepublic class RandomRule extends AbstractLoadBalancerRule随机选择一个server在index上随机,选择index对应位置的server
ZoneAvoidanceRulepublic class ZoneAvoidanceRule extends PredicateBasedRule复合判断server所在区域的性能和server的可用性选择server使用ZoneAvoidancePredicate和AvailabilityPredicate来判断是否选择某个server,前一个判断判定一个zone的运行性能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用于过滤掉连接数过多的Server。
3. feign介绍

spring cloud feign是一个基于Netflix Feign实现声明式的服务调用客户端
Feign 是一个声明web服务客户端,这便得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,Spring Cloud 增加了对 Spring MVC的注解,Spring Web 默认使用了HttpMessageConverters, Spring Cloud 集成 Ribbon 和 Eureka 提供的负载均衡的HTTP客户端 Feign.

服务消费实例

效果展示:
ribbon
ribbon
feign
在这里插入图片描述
1. 服务提供者

1.1 新建项目kp-producer,添加一下依赖
spring-boot-starter-web依赖
Swagger:api文档(可选)
Consul:注册中心
spring boot Admin:服务监控(可选)

注意:spring boot 使用 2.0.9.RELEASE admin-starter-client 使用2.0.6

<!--swagger 依赖-->
<!-- swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- 界面工具 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!--spring-boot-admin-client-->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>2.0.6</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Finchley.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencies>
</dependencyManagement>

1.2 修改配置文件,将服务注册到服务中心,并添加服务监控相关配置

# tomcat
server:
  port: 8003
spring:
  application:
    name: kp-producer
  boot:
    admin:
      client:
        url: "http://localhost:8000"
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name} #注册服务的名称
		# 开放健康检查接口
		management:
		  endpoints:
		    web:
		      exposure:
		        include: "*"
		  endpoint:
		    health:
		      show-details: always

1.3 启动类修改,添加注解@EnableDiscoveryClient 注解,开启服务发现支持

@SpringBootApplication
@EnableDiscoveryClient
public class KpPoducerApplication {
    public static void main(String[] args) {
        SpringApplication.run(KpProducerApplication.class, args);
    }

}

1.4 自定义banner,在banner.txt文件中

_____________  ____   __| _/_ __   ____  ___________ 
\____ \_  __ \/  _ \ / __ |  |  \_/ ___\/ __ \_  __ \
|  |_> >  | \(  <_> ) /_/ |  |  /\  \__\  ___/|  | \/
|   __/|__|   \____/\____ |____/  \___  >___  >__|   
|__|                     \/           \/    \/       

1.5 添加控制器,提供一个hello接口,返回字符串的信息 hello

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "hello  !";
    }
}

1.6 测试

为了模拟负载均衡,复制一份上面的上面的项目,重命名为kp-producer2,修改对应的端口为8004,修改hello方法返回字符串为 “hello 2”

依次启动注册中心console,和 2 个服务提供者。

访问注册中心http://localhost:8500 查看2个服务提供者是否注册到注册中心

访问http://localhost:8003/hello 输出hello 字符串

访问http://localhost:8004/hello 输出hello 2 字符串

2. 服务提供者

2.1 新建项目kp-consumer,添加一下依赖
spring-boot-starter-web依赖
Swagger:api文档(可选)
Consul:注册中心
spring boot Admin:服务监控(可选)

注意:spring boot 使用 2.0.9.RELEASE admin-starter-client 使用2.0.6

<!--swagger 依赖-->
<!-- swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- 界面工具 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!--spring-boot-admin-client-->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>2.0.6</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Finchley.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencies>
</dependencyManagement>

2.2 修改配置文件,将服务注册到服务中心,并添加服务监控相关配置

# tomcat

server:
  port: 8005
spring:
  application:
    name: kp-consumer
  boot:
    admin:
      client:
        url: "http://localhost:8000"
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name} #注册服务的名称
		# 开放健康检查接口
		management:
		  endpoints:
		    web:
		      exposure:
		        include: "*"
		  endpoint:
		    health:
		      show-details: always
		# 开放健康检查接口
​		management:
​		  endpoints:
​		    web:
​		      exposure:
​		        include: "*"
​		  endpoint:
​		    health:
​		      show-details: always

2.3 启动类修改,添加注解@EnableDiscoveryClient 注解,开启服务发现支持

@SpringBootApplication
@EnableDiscoveryClient
public class KpConsumerApplication {

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

}

2.4 自定义banner,在banner.txt文件中

  ____  ____   ____   ________ __  _____   ___________ 
_/ ___\/  _ \ /    \ /  ___/  |  \/     \_/ __ \_  __ \
\  \__(  <_> )   |  \\___ \|  |  /  Y Y  \  ___/|  | \/
 \___  >____/|___|  /____  >____/|__|_|  /\___  >__|   
     \/           \/     \/            \/     \/       

2.5 添加服务消费测试类,添加2个接口,一个查询所有我们注册的服务,一个从我们的服务中选取一个服务,采取轮询的方式

 	ServiceController.java

 	@RestController
	public class ServiceController {

	    @Autowired
	    private LoadBalancerClient loadBalancerClient;
	    @Autowired
	    private DiscoveryClient discoveryClient;

	   /**
	     * 获取所有服务
	     */
	    @RequestMapping("/services")
	    public Object services() {
	        return discoveryClient.getInstances("kp-producer");
	    }

	    /**
	     * 从所有服务中选择一个服务(轮询)
	     */
	    @RequestMapping("/discover")
	    public Object discover() {
	        return loadBalancerClient.choose("kp-producer").getUri().toString();
	    }
	}

2.6 测试

启动项目

访问注册中心http://localhost:8500 查看2个服务提供者是否注册到注册中心

访问http://localhost:8000,查看服务提供者是否已经成功显示在监控列表中

访问http://localhost:8005/services,返回2个服务,分别是我们注册的8003和8004

访问http://localhost:8005/discover 反复访问该地址,结果交替返回8003和8004的结果,从而实现了负载均衡

2.7 以上只是获取了该服务,但是没有调用到该服务的结果,因此我们模拟调用服务中的/hello方法,创建一个CallHelloController.java 使用RestTemplate 调用远程服务

@RestController
public class CallHelloController {

    @Autowired
    private LoadBalancerClient loadBalancer;

    @RequestMapping("/call")
    public String call() {
        ServiceInstance serviceInstance = loadBalancer.choose("kp-producer");
        System.out.println("服务地址:" + serviceInstance.getUri());
        System.out.println("服务名称:" + serviceInstance.getServiceId());

        String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class);
        System.out.println(callServiceResult);
        return callServiceResult;
    }

}

访问http://localhost:8005/call 获取服务提供的 ,多次访问,系统分别使用8003和8004提供服务

  1. resTemplate+ribbon服务调度

通过上面的例子,调用远程服务经历2个步骤,

首先通过LoadBalancerClient 查找服务实例,RibbonLoadBalancerClient是Ribbon的默认的负载均衡器

然后通过 RestTemplate 调用服务实例的控制器

3.1 为了操作方便,我们可以修改我们的启动类,添加@LoadBalanced注解,注入一个RestTemplate,使用ribbon做负载均衡

		@EnableDiscoveryClient
		@SpringBootApplication
		public class KpConsumerApplication {
	
		    public static void main(String[] args) {
		        SpringApplication.run(KpConsumerApplication.class, args);
		    }
	
		    @Bean
		    @LoadBalanced
		    public RestTemplate restTemplate(){
		        return new RestTemplate();
		    }
		}

3.2 新建一个控制器类,注入RestTemplate ,并调用服务提供者的hello服务

	@RestController
	public class RibbonHelloController {
	
	    @Autowired
	    private RestTemplate restTemplate;
	    
	    @RequestMapping("/ribbon/call")
	    public String call() {
	        // 调用服务, service-producer为注册的服务名称,LoadBalancerInterceptor会拦截调用并根据服务名找到对应的服务
	        String callServiceResult = restTemplate.getForObject("http://kp-producer/hello", String.class);
	        return callServiceResult;
	    }
	}

3.3 重启服务,访问http://localhost:8005/ribbon/call

3.4 如果需要修改策略,需要在application.yml 文件中添加策略类的名称就行,比如

service-producer:
	ribbon:
		NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
  1. Feign服务调度
    4.1 添加依赖
		<dependency>
	      <groupId>org.springframework.cloud</groupId>
	      <artifactId>spring-cloud-starter-openfeign</artifactId>
	    </dependency>

4.2 修改配置文件类,添加注解@EnableFeignClients 开启Feign的支持

		@EnableDiscoveryClient
		@SpringBootApplication
		@EnableFeignClients
		public class KpConsumerApplication {

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

		    @Bean
		    @LoadBalanced
		    public RestTemplate restTemplate(){
		        return new RestTemplate();
		    }
		}

4.3 创建一个接口 KpProducerService 使用 @FeignClient(name = “kp-producer”) 表示调用哪个服务在具体的方法中使用@RequestMapping("/hello") 调用服务器的访问地址

		@FeignClient(name = "kp-producer")
		public interface KpProducerService {

		    @RequestMapping("/hello")
		    public String hello();
		    
		}

4.4 创建FeignHelloController 用于测试Feign的调用,注入 KpProducerService,调用接口的方法,接口再调用远程服务

		@RestController
		public class FeignHelloController {

		    @Autowired
		    private KpProducerService kpProducerService;
		    
		    @RequestMapping("/feign/call")
		    public String call() {
		        // 像调用本地服务一样
		        return kpProducerService.hello();
		    }
		    
		}

4.5 重启服务,测试访问 访问http://localhost:8005/feign/call,访问的效果和前面例子的效果一样

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值