spring cloud中负载均衡Ribbon使用

spring cloud中负载均衡Ribbon使用

文章目录

  • spring cloud中负载均衡Ribbon使用
      • 一、简介
      • 二、步骤
        • 2.1 使用步骤
      • 三、示例
        • 3.1 注册中心
          • 3.1.1 maven依赖
          • 3.1.2 application.yaml配置
          • 3.1.3 启动类
        • 3.2 服务
          • 3.2.1 maven依赖
          • 3.2.2 application.yaml配置
          • 3.2.3 服务相关类
        • 3.3 客户端
          • 3.3.1 maven依赖
          • 3.3.2 application.yaml配置
          • 3.3.3 客户相关类
        • 3.4 测试
      • 四、备注
        • 4.1 常见问题
          • 4.1.1 defaultZone书写非驼峰导致错误
          • 4.1.2 服务名称有下划线导致错误

一、简介

spring cloud中,使用Ribbon作为负载均衡器,如果使用了feign,则自带负载均衡效果,开启即可。这里对Ribbon进行介绍。

二、步骤

2.1 使用步骤

开启负载均衡器步骤如下:

  1. 在创建RestTemplate的bean方法上添加负载均衡器注解@LoadBalanced
  2. 在服务调用时使用服务名(服务名不能有下划线,可为中划线),不能使用ip地址,否则不生效

三、示例

这里使用注册中心spring_cloud_register_center、服务spring_cloud_provider(运行多个实例)、客户端spring_cloud_client_ribbon(使用负载均衡器)进行示例。

3.1 注册中心

注册中心为spring_cloud_register_center项目。

3.1.1 maven依赖

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.2.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.dragon.studygroupId>
    <artifactId>spring_cloud_register_centerartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>spring_cloud_register_centername>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
        <spring-cloud.version>Hoxton.SR6spring-cloud.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
3.1.2 application.yaml配置
server:
  port: 8010
spring:
  application:
    name: spring-cloud-register-center
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:${server.port}/eureka/
    fetchRegistry: false #是否拉取注册信息,由于注册中心是单个结点,不需要拉取
    registerWithEureka: false #是否注册自己,由于当前就是注册中心,帮不需要注册
3.1.3 启动类
package com.dragon.study.spring_cloud_register_center;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class SpringCloudRegisterCenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudRegisterCenterApplication.class, args);
    }
}

3.2 服务

服务为spring_cloud_provider项目。

3.2.1 maven依赖

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.2.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.dragon.studygroupId>
    <artifactId>spring_cloud_providerartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>spring_cloud_providername>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
        <spring-cloud.version>Hoxton.SR6spring-cloud.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.6version>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
3.2.2 application.yaml配置
server:
  port: 8011
spring:
  application:
    name: spring-cloud-provider
eureka:
  instance:
    prefer-ip-address: true #true表示使用ip注册,若为false,则表示使用系统hostname注册
  client:
    service-url:
      default-zone: http://localhost:8010/eureka/
management:
  endpoints:
    web:
      exposure:
        include: "*"
3.2.3 服务相关类

定义实体bean类Stu.java

package com.dragon.study.spring_cloud_provider.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Stu {
    private String stuId;
    private  Integer age;
}

定义服务controller类StuController.java

package com.dragon.study.spring_cloud_provider.controller;
import com.dragon.study.spring_cloud_provider.bean.Stu;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("stu")
public class StuController {
    @RequestMapping("getStu")
    private Object getStu(Stu stu) {
        System.out.println(stu);
        return stu;
    }
}

定义启动类SpringCloudProviderApplication.java

package com.dragon.study.spring_cloud_provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudProviderApplication.class, args);
    }
}

启动,这里启动两个实例,只是端口号不一样,分别为8011和8021,在application.yaml中修改。

3.3 客户端

客户端为spring_cloud_client_ribbon项目。

3.3.1 maven依赖

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.2.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.dragon.studygroupId>
    <artifactId>spring_cloud_client_ribbonartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>spring_cloud_client_ribbonname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
        <spring-cloud.version>Hoxton.SR6spring-cloud.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-ribbonartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.62version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.4version>
            <scope>compilescope>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
3.3.2 application.yaml配置
server:
  port: 8051
spring:
  application:
    name: spring-cloud-ribbon-client
eureka:
  instance:
    preferIpAddress: true #true表示使用ip注册,若为false,则表示使用系统hostname注册
  client:
    serviceUrl:
      defaultZone: http://localhost:8010/eureka/
3.3.3 客户相关类

定义实体bean

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Stu {
    private String stuId;
    private  Integer age;
}

定义启动类

package com.dragon.study.spring_cloud_ribbon_client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class SpringCloudRibbonClientApplication {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudRibbonClientApplication.class, args);
    }
}

定义调用服务类

package com.dragon.study.spring_cloud_ribbon_client.controller;
import com.alibaba.fastjson.JSON;
import com.dragon.study.spring_cloud_ribbon_client.bean.Stu;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.Map;
@RestController
@RequestMapping("stu")
public class StuController {
    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("getStu")
    public Object getStu(Stu stu) {
        Map<String, Object> m = JSON.parseObject(JSON.toJSONString(stu), Map.class);
        return restTemplate.postForObject("http://spring-cloud-provider/stu/getStu?stuId={stuId}&age={age}", null, Stu.class, m);
    }
}

3.4 测试

依次启动注册中心spring_cloud_register_center、服务spring_cloud_provider(运行多个实例)、客户端spring_cloud_client_ribbon。
测试:

#在客户端多次调用服务
GET http://localhost:8051/stu/getStu?stuId=001&age=17
Accept: application/json

可以发现在服务端多个实例有调用输出,说明负载均衡生效了。

四、备注

4.1 常见问题

4.1.1 defaultZone书写非驼峰导致错误

报错:

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server

解决:

将application.yaml中的default-zone书写改为驼峰形式defaultZone
4.1.2 服务名称有下划线导致错误

报错:

java.lang.IllegalStateException: Request URI does not contain a valid hostname:

解决:

ribbon实现负载均衡时,服务名称不能有下划线,可改为中划线

你可能感兴趣的:(微服务)