当前位置: 代码迷 >> 综合 >> SpringCloud 第三篇: 服务消费者(Ribbon / Feign)
  详细解决方案

SpringCloud 第三篇: 服务消费者(Ribbon / Feign)

热度:51   发布时间:2023-10-25 16:21:56.0

        前面的文章学习了服务的注册和发现。在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。在这一篇文章要学习的是如何 通过 rest + ribbon 和 Feign 来消费服务,也就是跨服务调用。

1. Rest + Ribbon

1.1 Ribbon 简介

        ribbon 是一个客户端负载均衡器,可以简单的理解成类似于 nginx的负载均衡模块的功能,可以很好的控制http和tcp的一些行为。

1.2 创建服务消费者

在之前那个项目里面创建一个Module,和之前创建服务相似的过程,注意下要导入Ribbon所需的包。


创建完成之后的 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"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>demoRibbon</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><spring-cloud.version>Finchley.BUILD-SNAPSHOT</spring-cloud.version></properties><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build><repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><snapshots><enabled>true</enabled></snapshots></repository><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories></project>

1.3 添加注解

        在服务的启动类中,通过 @EnableDiscoveryClient 指向服务中心注册,并且向程序的 ioc 注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。

package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
@EnableEurekaClient
public class DemoRibbonApplication {public static void main(String[] args) {SpringApplication.run(DemoRibbonApplication.class, args);}@Bean@LoadBalancedRestTemplate restTemplate(){return new RestTemplate();}
}

1.4 配置信息

eureka:client:serviceUrl:defaultZone: http://localhost:10000/eureka/
server:port: 10001
spring:application:name: service-demo

1.5 测试

        写一个测试类HelloController,通过之前注入ioc容器的restTemplate来消费service-demo服务的“/hello”接口,在这里我们直接用的服务名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名,如果服务名带有下划线都无法调用成功,代码如下:

package com.example.demo.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;@RestController
public class HelloController {@AutowiredRestTemplate restTemplate;@RequestMapping("/wlecome")public String wlecome(@RequestParam String name){String wlecome = restTemplate.getForObject("http://SERVICE-DEMO/hello?name="+name, String.class);return wlecome;}
}

在浏览器上访问 http://localhost:10002/wlecome?name=yangling ,页面打印出:


 由于我们代码输出的是的service-demo服务的端口号,所以 prot 显示的是10001。

        这说明当我们通过调用 restTemplate.getForObject("http://SERVICE-DEMO/hello?name="+name, String.class) 方法时,已经做了负载均衡,访问了不同的端口的服务实例。

2. Feign

2.1 Feign简介

        官网里面解释:Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。

总结就是:

        1. Feign 采用的是基于接口的注解;

        2. Feign 可以和其他的开源工具集成工作;

        3. Feign 整合了ribbon。

2.2 创建消费者服务

创建一个Module,和之前创建服务相似的过程,注意下要导入Feign所需的包。


创建完成之后的 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"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>demoFeign</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><spring-cloud.version>Finchley.BUILD-SNAPSHOT</spring-cloud.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build><repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><snapshots><enabled>true</enabled></snapshots></repository><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories></project>

2.3 添加注解

在服务的启动类中,通过@EnableDiscoveryClient向服务中心注册,加上@EnableFeignClients注解开启Feign的功能:

package com.example.feign;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class DemoFeignApplication {public static void main(String[] args) {SpringApplication.run(DemoFeignApplication.class, args);}
}

2.4 配置信息

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

2.5 测试

        定义一个feign接口,通过@FeignClient(“服务名”),来指定调用哪个服务,需要注意的是如果调用的服务名带有下划线在启动时会报错。比如在代码中调用了service-demo服务的“/hello”接口,代码如下:

package com.example.feign.feign;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;@FeignClient("service-demo")//访问的服务名如果带有下划线启动会报错
public interface SchedualServiceHello {@RequestMapping(value = "/hello",method = RequestMethod.GET)String sayHelloFromClientOne(@RequestParam(value = "name") String name);
}
写一个测试Controll,通过上面定义的Feign客户端SchedualServiceHi 来消费服务。代码如下:
package com.example.feign.controller;import com.example.feign.feign.SchedualServiceHello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class FeignController {@AutowiredSchedualServiceHello schedualServiceHello;String port;@RequestMapping("/hello")public String home(@RequestParam String name) {return schedualServiceHello.sayHelloFromClientOne(name);}
}

在浏览器上访问 http://localhost:10003/hello?name=feign ,页面打印出:


3 总结

通过 Rest+Ribbon 和 Feign, 我们能把HTTP远程调用对开发者完全透明,得到与调用本地方法一致的编码体验。这一点与阿里Dubbo中暴露远程服务的方式类似,区别在于Dubbo是基于私有二进制协议,而它们本质上还是个HTTP客户端。如果是在用Spring Cloud Netflix搭建微服务,一般我们选择 Feign 。

  相关解决方案