SpringCloud框架搭建(三)服务消费ribbon和feign

Ribbon

Ribbon 是一个基于 HTTP 和 TCP 客户端的负载均衡器,它可以在客户端配置 ribbonServerList(服务端列表),然后轮询请求以实现均衡负载,它在联合 Eureka 使用时ribbonServerList 会被 DiscoveryEnabledNIWSServerList 重写,扩展成从 Eureka 注册中心获取服务端列表 同时它也会用 NIWSDiscoveryPing 来取代 IPing,它将职责委托给 Eureka 来确定服务端是否已经启动

首先在pom里面加入

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

然后声明一个RestTemplate负责远程调用

然后使用

restTemplate.getForObject("http://127.0.0.1:8083/getConfig",String.class);

就可以远程调用服务了。当然这样并不是负载均衡,每次请求只能发到http://127.0.0.1:8083这个服务上。所以我们要在声明RestTemplate的时候加一个@LoadBalanced注解,使用的时候不要用具体的ip端口,而是要托管给eureka,即使用eureka实例名称

restTemplate.getForObject("http://eureka-points/getConfig",String.class);

这样才真正的整合了ribbon实现负载均衡,请求eureka-points的时候会在服务列表里面轮询请求eureka-points实例以实现均衡负载。

Feign

Spring Cloud Netflix 的微服务都是以 HTTP 接口的形式暴露的,所以可以用 Apache 的 HttpClient 或 Spring 的 RestTemplate 去调用,而 Feign 是一个使用起来更加方便的http客户端,它使用起来就像调用本地接口一样。spring-cloud-starter-feign 里面已经包含了 spring-cloud-starter-ribbon(Feign 中也使用了 Ribbon).

当我们通过RestTemplate调用其它服务的API时,所需要的参数须在请求的URL中进行拼接,如果参数少的话或许我们还可以忍受,一旦有多个参数的话,这时拼接请求字符串就会效率低下,并且容易出错。这个时候我们就会用到Feign,Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数、格式、地址等信息。

而Feign则会完全代理HTTP请求,我们只需要像调用方法一样调用它就可以完成服务请求及相关处理。Feign整合了Ribbon和Hystrix,可以让我们不再需要显式地使用这两个组件。

总起来说,Feign具有如下特性:

1。可插拔的注解支持,包括Feign注解和JAX-RS注解;

2。支持可插拔的HTTP编码器和解码器;

3。支持Hystrix和它的Fallback;

4。支持Ribbon的负载均衡;

5。支持HTTP请求和响应的压缩。

首先在我们的pom里面加入

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

然后编写Feign接口

package com.cjc.spring.cloud.user.service.feign;

import com.cjc.spring.cloud.user.service.hystrix.UserPointsHystrix;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient(value = "eureka-points")
public interface UserPointsFeign {
    @RequestMapping("/getPoints")
    public  String getPoints();
}

其中@FeignClient表示要调用哪个微服务,@RequestMapping代表要调用的服务的接口

然后在我们的启动类上加上

@EnableFeignClients(basePackages = "com.cjc.spring.cloud.user.service.feign")

启动Feign并且指定扫描的包。

这样我们就可以注入这个Feign,并且调用相关的接口

@Autowired
private UserPointsFeign userPoints;
userMessageService.getUserMessage()

源码下载:https://github.com/cxsummer/springcloud

猜你喜欢

转载自blog.csdn.net/cjc000/article/details/91359921