当前位置: 移动技术网 > IT编程>开发语言>Java > SpringCloud学习系列之二 ----- 服务消费者(Feign)和负载均衡(Ribbon)

SpringCloud学习系列之二 ----- 服务消费者(Feign)和负载均衡(Ribbon)

2019年01月16日  | 移动技术网IT编程  | 我要评论

前言

本篇主要介绍的是springcloud中的服务消费者(feign)和负载均衡(ribbon)功能的实现以及使用feign结合ribbon实现负载均衡。

springcloud feign

feign 介绍

feign是一个声明式的web service客户端,它使得编写web serivce客户端变得更加简单。我们只需要使用feign来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括feign注解和jax-rs注解。feign也支持可插拔的编码器和解码器。spring cloud为feign增加了对spring mvc注解的支持,还整合了ribbon和eureka来提供均衡负载的http客户端实现。

开发准备

开发环境

  • jdk:1.8
  • springboot:2.1.1.release
  • springcloud:finchley

注:不一定非要用上述的版本,可以根据情况进行相应的调整。需要注意的是springboot2.x以后,jdk的版本必须是1.8以上!

确认了开发环境之后,我们再来添加相关的pom依赖。

<dependencies>
    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter</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>
</dependencies>

注: 基于springboot1.x以上springcloud是dalston版本的eureka 依赖是 <artifactid>spring-cloud-starter-eureka</artifactid>,feign 依赖是 <artifactid>spring-cloud-starter-feign</artifactid> ,少了个 netflix 。springcloud的版本命名方式是通过伦敦的地方来命名的,版本顺序是根据首字母的顺序来的。

springcloud feign 示例

服务端

首先建立一个springcloud-feign-eureka服务的工程,用于做注册中心。配置和之前的基本一样。application.properties添加如下的配置:

配置信息:

spring.application.name=springcloud-feign-eureka-server
server.port=8001
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceurl.defaultzone=http://localhost:8001/eureka/

配置说明:

  • spring.application.name: 这个是指定服务名称。
  • server.port:服务指定的端口。
  • eureka.client.register-with-eureka:表示是否将自己注册到eureka server,默认是true。
  • eureka.client.fetch-registry:表示是否从eureka server获取注册信息,默认为true。
  • eureka.client.serviceurl.defaultzone: 这个是设置与eureka server交互的地址,客户端的查询服务和注册服务都需要依赖这个地址。

完成配置信息的添加后,我们再来看代码如何实现。
在服务端这边只需要在springboot启动类添加@enableeurekaserver注解就可以了,该注解表示此服务是一个服务注册中心服务。

代码示例:

    @enableeurekaserver
    @springbootapplication
    public class feigneurekaapplication {
      public static void main(string[] args) {
          springapplication.run(feigneurekaapplication.class, args);
          system.out.println("feign注册中心服务启动...");
      }
    }

客户端

这里我们定义两个消费者,springcloud-feign-consumerspringcloud-feign-consumer2,一个使用feign做转发,另一个为一个普通的项目。 添加如上的依赖之后,在application.properties添加如下的配置:

consumer 配置信息:

spring.application.name=springcloud-feign-consumer
server.port=9002
eureka.client.serviceurl.defaultzone=http://localhost:8001/eureka/

consumer2 配置信息:

spring.application.name=springcloud-feign-consumer2
server.port=9003
eureka.client.serviceurl.defaultzone=http://localhost:8001/eureka/

配置说明:

  • spring.application.name: 这个是客户端的服务名称。如果有多个服务使用同一个名称但是访问地址不同,结合ribbon 使用,则可以实现负载均衡功能。
  • server.port:服务指定的端口。
  • eureka.client.serviceurl.defaultzone: 注册中心服务端的地址。
springcloud-feign-consumer

springcloud-feign-consumer服务因为要实现fegin的功能,因此需要在启动类上添加@enablefeignclients该注解,使用该注解表示启用feign进行远程调用。

启动类代码示例:

    @springbootapplication
    @enablediscoveryclient
    @enablefeignclients
    public class feignconsumerapplication {
        public static void main(string[] args) {
            springapplication.run(feignconsumerapplication.class, args);
              system.out.println("feign第一个消费者服务启动...");
        }
    }

需要定义转发的服务,这里使用@feignclient注解来实现,该注解表示需要转发服务的名称,该名称在application.properties中进行配置。
这里我们把请求转发到第二个服务springcloud-feign-consumer2

转发类代码示例:

    @feignclient(name= "springcloud-feign-consumer2") 
    public interface helloremote {
        @requestmapping(value = "/hello")
         public string hello(@requestparam(value = "name") string name);
    }

我们还需要提供一个入口供外部调用,然后调用上述的的方法进行转发。

控制层代码示例:

    @restcontroller
    public class consumercontroller {
    
        @autowired
        helloremote helloremote;
        
        @requestmapping("/hello/{name}")
        public string index(@pathvariable("name") string name) {
            system.out.println("接受到请求参数:"+name+",进行转发到其他服务");
            return helloremote.hello(name);
        }
    }
springcloud-feign-consumer2

这个服务的代码就比较简单了,只是一个普通的服务,提供一个接口然后打印信息即可。

启动类代码示例:

    @springbootapplication
    @enablediscoveryclient
    public class feignconsumerapplication2 {
        public static void main(string[] args) {
            springapplication.run(feignconsumerapplication2.class, args);
              system.out.println("feign第二个消费者服务启动...");
        }
    }

控制层代码示例:

    @restcontroller
    public class consumercontroller {
    
        @requestmapping("/hello")
        public string index(@requestparam string name) {
            return name+",hello world";
        }
    }

功能测试

完成如上的工程开发之后,我们依次启动服务端和客户端的三个程序,然后在浏览器界面输入:http://www.lhsxpumps.com/_localhost:8001/,即可查看注册中心的信息。

在浏览器输入:

http://localhost:9003/hello?name=pancm

返回:

pancm,hello world

说明可以直接访问第二个消费服务。

然后再输入:

http://localhost:9002/hello/pancm

通过第一个消费服务调用第二个服务。

控制台打印:

接受到请求参数:pancm,进行转发到其他服务

界面返回结果:

pancm,hello world

示例图:

在这里插入图片描述

在这里插入图片描述

出现以上结果说明客户端已经成功的通过feign调用了远程服务hello,并且将结果返回到了浏览器。

springcloud ribbon

ribbon 介绍

ribbon是netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将netflix的中间层服务连接在一起。ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出load balancer后面所有的机器,ribbon会自动的帮助你基于某种规则(如简单轮询,随即连接等)去连接这些机器。我们也很容易使用ribbon实现自定义的负载均衡算法。简单地说,ribbon是一个客户端负载均衡器。

开发准备

开发环境

  • jdk:1.8
  • springboot:2.1.1.release
  • springcloud:finchley

注:不一定非要用上述的版本,可以根据情况进行相应的调整。需要注意的是springboot2.x以后,jdk的版本必须是1.8以上!

确认了开发环境之后,我们再来添加相关的pom依赖。

<dependencies>
    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter-netflix-eureka</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-actuator</artifactid>
    </dependency>
</dependencies>

注: 基于springboot1.x以上springcloud是dalston版本的eureka 依赖是 <artifactid>spring-cloud-starter-eureka</artifactid>,feign 依赖是 <artifactid>spring-cloud-starter-ribbon</artifactid> ,少了个 netflix 。springcloud的版本命名方式是通过伦敦的地方来命名的,版本顺序是根据首字母的顺序来的。

springcloud ribbon 示例

服务端

首先建立一个springcloud-ribbon-eureka服务的工程,用于做注册中心。配置和代码之前的基本一样,除了端口和打印信息,这里就不在说明了。

客户端

这里我们定义三个服务,一个服务使用ribbon做负载均衡,另外两个做普通的服务,服务名称依次为springcloud-ribbon-consumerspringcloud-ribbon-consumer2springcloud-ribbon-consumer3。 添加如上的依赖之后,在application.properties添加如下的配置:

consumer 配置信息:

spring.application.name=springcloud-ribbon-consumer
server.port=9006
eureka.client.serviceurl.defaultzone=http://localhost:8003/eureka/

consumer2 配置信息:

spring.application.name=springcloud-ribbon-consumer2
server.port=9007
eureka.client.serviceurl.defaultzone=http://localhost:8003/eureka/

consumer3 配置信息:

这里的服务名称和另一个服务的名称保持一致才能实现负载均衡功能。

spring.application.name=springcloud-ribbon-consumer2
server.port=9008
eureka.client.serviceurl.defaultzone=http://localhost:8003/eureka/

配置说明:

  • spring.application.name: 这个是客户端的服务名称。如果有多个服务使用同一个名称但是访问地址不同,结合ribbon 使用,则可以实现负载均衡功能。
  • server.port:服务指定的端口。
  • eureka.client.serviceurl.defaultzone: 注册中心服务端的地址。
springcloud-ribbon-consumer

使用ribbon实现负载均衡,只需要在启动类中实例化resttemplate,通过@loadbalanced注解开启均衡负载能力.。

启动类代码示例:

    @springbootapplication
    @enablediscoveryclient
    public class ribbonconsumerapplication {
        public static void main(string[] args) {
            springapplication.run(ribbonconsumerapplication.class, args);
            system.out.println("ribbon第一个消费者服务启动...");
        }
    
        @bean
        @loadbalanced
        public resttemplate resttemplate() {
            return new resttemplate();
        }
    }

需要定义转发的服务,这里使用resttemplate来进行调用,调用另外一个服务的名称。

转发类代码示例:

    @restcontroller
    public class consumercontroller {
       
        @autowired
        resttemplate resttemplate;
        
        @requestmapping("/hello")
        public string hello() {
            //进行远程调用
            return resttemplate.getforobject("http://springcloud-ribbon-consumer2/hello/?name=xuwujing", string.class);
        }
    }
    

springcloud-ribbon-consumer2springcloud-ribbon-consumer3代码基本和fegin中的springcloud-feign-consumer一样,因此这里就不在贴代码了。

功能测试

完成如上的工程开发之后,我们依次启动服务端和客户端的四个程序,然后在浏览器界面输入:http://localhost:8003/,即可查看注册中心的信息。

在浏览器输入:

http://localhost:9006//hello

然后进行重复访问,返回如下结果:

xuwujing,hello world!
xuwujing,hello world! 这是另一个服务!
xuwujing,hello world!
xuwujing,hello world! 这是另一个服务!
xuwujing,hello world!
xuwujing,hello world! 这是另一个服务!

说明已经实现了负载均衡功能了。

我们从上述的结果中发现了一点,这个调用貌似是有规律的,两个服务进行来回调用。那么根据这个我们发现了,负载均衡是由策略的。上述的这个示例的策略就是其中的一个roundrobinrule轮询策略。

这里就顺便说下ribbon的策略,ribbon一共有7中策略,默认使用的策略是轮询。策略说明如下表格:

策略名 策略声明 策略描述 实现说明
bestavailablerule public class bestavailablerule extends clientconfigenabledroundrobinrule 选择一个最小的并发请求的server 逐个考察server,如果server被tripped了,则忽略,在选择其中activerequestscount最小的server
availabilityfilteringrule public class availabilityfilteringrule extends predicatebasedrule 过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值) 使用一个availabilitypredicate来包含过滤server的逻辑,其实就就是检查status里记录的各个server的运行状态
weightedresponsetimerule public class weightedresponsetimerule extends roundrobinrule 根据响应时间分配一个weight,响应时间越长,weight越小,被选中的可能性越低。 一个后台线程定期的从status里面读取评价响应时间,为每个server计算一个weight。weight的计算也比较简单responsetime 减去每个server自己平均的responsetime是server的权重。当刚开始运行,没有形成status时,使用roubine策略选择server。
retryrule public class retryrule extends abstractloadbalancerrule 对选定的负载均衡策略机上重试机制。 在一个配置时间段内当选择server不成功,则一直尝试使用subrule的方式选择一个可用的server
roundrobinrule public class roundrobinrule extends abstractloadbalancerrule roundrobin方式轮询选择server 轮询index,选择index对应位置的server
randomrule public class randomrule extends abstractloadbalancerrule 随机选择一个server 在index上随机,选择index对应位置的server
zoneavoidancerule public class zoneavoidancerule extends predicatebasedrule 复合判断server所在区域的性能和server的可用性选择server 使用zoneavoidancepredicate和availabilitypredicate来判断是否选择某个server,前一个判断判定一个zone的运行性能是否可用,剔除不可用的zone(的所有server),availabilitypredicate用于过滤掉连接数过多的server。

这里也顺便说明如何指定一个策略使用方法。

最简单的方式

application.properties添加如下配置:

springcloud-ribbon-consumer2.ribbon.nfloadbalancerruleclassname=com.netflix.loadbalancer.randomrule

该配置的意思是为springcloud-ribbon-consumer2服务指定随机策略。

另一种方式

新建一个类,通过@bean注解指定策略。

    @configuration
    public class ribbonconfiguration{
          @bean
          public irule ribbonrule(){        
              return new randomrule();
         }
    }

然后再通过@ribbonclien注解指定服务。

    @ribbonclient(name="springcloud-ribbon-consumer2", configuration=ribbonconfiguration.class)
    public class helloribbon{    
    }

注: 如果有的服务没有在eureka进行注册,可以使用ribbon.listofservers方式在配置文件中来指定服务。

例如:

springcloud-ribbon-consumer2.ribbon.listofservers:localhost:9007,localhost:9008

添加好了该配置之后,我们重启springcloud-ribbon-consumer服务,然后依旧重复访问 http://localhost:9006//hello 该地址,
访问的结果如下:

xuwujing,hello world!
xuwujing,hello world! 这是另一个服务!
xuwujing,hello world! 这是另一个服务!
xuwujing,hello world!
xuwujing,hello world!
xuwujing,hello world!

可以看到已经成功实现了随机访问的策略!

springcloud fegin结合ribbon实现负载均衡

fegin包含了ribbon,可以直接实现负载均衡功能。这里我们就在ribbon的项目稍微进行改造下实现该功能。

首先在pom文件添加fegin的依赖包。

    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter-openfeign</artifactid>
    </dependency>

然后在springcloud-ribbon-consumer项目的启动类上添加@enablefeignclients注解,启用feign进行远程调用。

添加完成之后,新建一个类,实现feign远程调用。
代码如下:

    @feignclient(name= "springcloud-ribbon-consumer2") 
    public interface helloremote {
        @requestmapping(value = "/hello")
        public string hello(@requestparam(value = "name") string name);
    }

最后在提供一个新的接口供外部调用。这里就直接在之前的代码上新加一个接口了。
代码如下:

    @restcontroller
    public class consumercontroller {
       
        @autowired
        resttemplate resttemplate;
        
        @requestmapping("/hello")
        public string hello() {
            return resttemplate.getforobject("http://springcloud-ribbon-consumer2/hello/?name=xuwujing", string.class);
        }
        
       
        @autowired
        helloremote helloremote;
        
        @requestmapping("/hello/{name}")
        public string index(@pathvariable("name") string name) {
            system.out.println("接受到请求参数:"+name+",进行转发到其他服务!");
            return helloremote.hello(name);
        }
    }

添加完之后,重启springcloud-ribbon-consumer服务,然后依旧重复访问 http://www.lhsxpumps.com/_localhost:9006//hello/pancm 该地址,
访问的结果如下:

pancm,hello world!
pancm,hello world! 这是另一个服务!
pancm,hello world!
pancm,hello world! 这是另一个服务!
pancm,hello world!
pancm,hello world! 这是另一个服务!

示例图:
在这里插入图片描述

在这里插入图片描述

其他

项目地址

基于springboot1.x、springcloud的dalston版本:https://github.com/xuwujing/springcloud-study

基于springboot1.x、springcloud 的dalston版本: https://github.com/xuwujing/springcloud-study-old

如果感觉项目不错,希望能给个star,谢谢!

音乐推荐

一首非常棒的纯音乐 next to you ,强烈推荐!

原创不易,如果感觉不错,希望给个推荐!您的支持是我写作的最大动力!
版权声明:
作者:虚无境
博客园出处:http://www.cnblogs.com/xuwujing
csdn出处:http://blog.csdn.net/qazwsxpcm    
个人博客出处:http://www.panchengming.com

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网