SpringCloud-負載均衡Robbin

SpringCloud-負載均衡Robbin

項目結構

在這裏插入圖片描述
在這裏插入圖片描述

父工程(每一個服務都是一個子工程)

  1. 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.xiaoge.demo</groupId>
        <artifactId>cloud-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
        <modules>
            <module>user-service</module>
            <module>consumer-demo</module>
            <module>eureka-server</module>
        </modules>
        <packaging>pom</packaging>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.4.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.SR1</spring-cloud.version>
            <mapper.starter.version>2.0.3</mapper.starter.version>
            <mysql.version>5.1.32</mysql.version>
        </properties>
    
        <dependencyManagement> <!-- 所有子工程, 必須引下面的依賴纔會有 -->
            <dependencies>
                <!-- spring cloud 引用了它, 以後cloud依賴版本就不用寫了 -->
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
    
                <!-- 通用Mapper啓動器 -->
                <dependency>
                    <groupId>tk.mybatis</groupId>
                    <artifactId>mapper-spring-boot-starter</artifactId>
                    <version>${mapper.starter.version}</version>
                </dependency>
    
                <!-- mysql驅動 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>${mysql.version}</version>
                </dependency>
    
            </dependencies>
        </dependencyManagement>
    
        <dependencies> <!-- 因爲不會再dependencyManagement標籤裏, 所以所有的子工程都可以用 -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

consumer-demo服務

  1. 配置文件

    1. 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">
          <parent>
              <artifactId>cloud-demo</artifactId>
              <groupId>com.xiaoge.demo</groupId>
              <version>1.0-SNAPSHOT</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
      
          <artifactId>consumer-demo</artifactId>
      
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
      
              <!-- 引入eureka客戶端依賴 -->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
              </dependency>
      
              <!-- 引入負載均衡 ribbon -->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
              </dependency>
      
          </dependencies>
      
      </project>
      
    2. application.yml

      server:
        port: 8088
      spring:
        # 在eureka中註冊的服務名稱
        application:
          name: consumer-service
      
      # 註冊方
      # eureka配置 因爲它要去註冊中心註冊, 所以要配置
      eureka:
        client:
          service-url:
            defaultZone: http://127.0.0.1:10086/eureka, http://127.0.0.1:10087/eureka # 配置所有的eureka地址, 防止其中一個eureka掛掉
          registry-fetch-interval-seconds: 3 # 設置拉取服務列表的週期 爲3秒
          fetch-registry: true # 默認爲true 拉取列表, 改爲false 不拉取
        instance:
          prefer-ip-address: true # 我希望使用ip地址
          ip-address: 127.0.0.1 # 設置ip地址
      # 對那個服務實現負載均衡
      user-service: # 對user-service服務 (服務名稱)
        ribbon: # 固定寫法
          NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 使用負載均衡隨機算法, 默認是輪詢
      
  2. 啓動類

    1. ConsumerApplication

      package com.xiaoge;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
      import org.springframework.cloud.client.loadbalancer.LoadBalanced;
      import org.springframework.context.annotation.Bean;
      import org.springframework.web.client.RestTemplate;
      
      /**
       * @program: cloud-demo
       * @description: 服務調用方
       * @author: Mr.Xiao
       * @create: 2020-05-04 16:04
       **/
      @EnableDiscoveryClient // 它也是客戶端, 它捷能兼容eureka 又能consul、zookeeper等等, 更通用, 更廣泛
      @SpringBootApplication
      public class ConsumerApplication {
      
          @Bean
          @LoadBalanced // 加上ribbon 負載均衡註解
          public RestTemplate restTemplate() {
              return new RestTemplate();
          }
      
          public static void main(String[] args) {
              SpringApplication.run(ConsumerApplication.class);
          }
      
      }
      
      
  3. 實體類

    1. User

      package com.xiaoge.Consumer.pojo;
      
      import lombok.Data;
      
      import java.io.Serializable;
      import java.util.Date;
      
      /**
       * @program: cloud-demo
       * @description:
       * @author: Mr.Xiao
       * @create: 2020-05-04 16:06
       **/
      @Data
      public class User implements Serializable {
          // 主鍵
          private Long id;
      
          // 用戶名
          private String username;
      
          // 密碼
          private String password;
      
          // 姓名
          private String name;
      
          // 年齡
          private Integer age;
      
          // 性別,1男性,2女性
          private Integer sex;
      
          // 出生日期
          private Date birthday;
      
          // 創建時間
          private Date created;
      
          // 更新時間
          private Date updated;
      
          // 備註
          private String note;
      
      }
      
  4. 表現層

    1. ConsumerController

      package com.xiaoge.Consumer.controller;
      
      import com.xiaoge.Consumer.pojo.User;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.cloud.client.discovery.DiscoveryClient;
      import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;
      import org.springframework.web.client.RestTemplate;
      
      import java.util.List;
      
      /**
       * @program: cloud-demo
       * @description: 動態拉取服務列表
       * @author: Mr.Xiao
       * @create: 2020-05-04 16:08
       **/
      @RestController
      @RequestMapping("/consumer")
      public class ConsumerController {
      
          @Autowired
          private RestTemplate restTemplate;
      
          @Autowired
          private DiscoveryClient discoveryClient; // 專門負責服務發現
      
          //@Autowired
          //private RibbonLoadBalancerClient client; // 專門負責 負載均衡 獲取服務的
      
         /*
             @GetMapping("/{id}")
              public User queryById(@PathVariable("id") Long id){
                  // 拉取服務  根據服務id獲取實例
                  List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
      
                  // 獲取第一個實例, 從實例當中取出ip和端口
                  ServiceInstance instance = instances.get(0); // 這個位置正常情況下, 要寫負載均衡算法, 我這裏是隨便取得
      
                  // 獲取ip
                  String ip = instance.getHost();
      
                  // 獲取端口
                  int port = instance.getPort();
      
                  // 訪問的地址
                  String url = "http://" + ip + ":" + port;
      
                  User user = restTemplate.getForObject(url + "/user/" + id, User.class);
                  return user;
              }
          */
      
          /*
              @GetMapping("/{id}")
              public User queryById(@PathVariable("id") Long id){
                  // 負載均衡算法: 隨機, 輪詢. hash
      
                  // 拉取服務  根據服務id獲取實例
                  ServiceInstance instance = client.choose("user-server"); // 默認使用的輪詢
      
                  // 獲取ip
                  String ip = instance.getHost();
      
                  // 獲取端口
                  int port = instance.getPort();
      
                  // 訪問的地址
                  String url = "http://" + ip + ":" + port;
      
                  User user = restTemplate.getForObject(url + "/user/" + id, User.class);
                  return user;
              }
          */
      
          @GetMapping("/{id}")
          public User queryById(@PathVariable("id") Long id){
              // 負載均衡算法: 隨機, 輪詢. hash
      
              // 1. 在註冊restTemplate上加註解@LoadBalanced
      
              // 2. 直接寫路徑
              String url = "http://user-service/user/" + id;
              User user = restTemplate.getForObject(url, User.class);
              return user;
          }
      
      }
      
      

eureka-server服務

  1. 配置文件

    1. 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">
          <parent>
              <artifactId>cloud-demo</artifactId>
              <groupId>com.xiaoge.demo</groupId>
              <version>1.0-SNAPSHOT</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
      
          <artifactId>eureka-server</artifactId>
      
          <dependencies>
              <!-- springcloud 註冊中心 eureka -->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
              </dependency>
          </dependencies>
      
      </project>
      
    2. application.yml

      # 這是eureka的默認端口號
      server:
        port: 10086
      
      # 配置eureka服務名稱
      spring:
        application:
          name: eureka-server
      
      # 註冊方
      # 告訴eureka要註冊的地址在哪裏 (這樣eureka就不會報一個com.sun.jersey.api.client.ClientHandlerException異常)
      eureka:
        client:
          service-url:
            defaultZone: http://127.0.0.1:10086/eureka # 配置所有的eureka地址, 防止其中一個eureka掛掉
          register-with-eureka: false  # 默認爲true 註冊自己, 改爲false 不 註冊自己
        instance:
          prefer-ip-address: true # 我希望使用ip地址
          ip-address: 127.0.0.1 # 設置ip地址
        server:
          eviction-interval-timer-in-ms: 60000 # 設置eureka失效剔除時長, 每隔60秒失效剔除一次, 失效剔除掛掉的eureka
      
  2. 啓動類

    1. EurekaServer

      package com.xiaoge;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
      
      /**
       * @program: cloud-demo
       * @description: EurekaServer端
       * @author: Mr.Xiao
       * @create: 2020-05-04 16:34
       **/
      @EnableEurekaServer // 啓動Eureka服務
      @SpringBootApplication
      public class EurekaServer {
      
          public static void main(String[] args) {
              SpringApplication.run(EurekaServer.class);
          }
      
      }
      

user-service服務

  1. 配置文件

    1. 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">
          <parent>
              <artifactId>cloud-demo</artifactId>
              <groupId>com.xiaoge.demo</groupId>
              <version>1.0-SNAPSHOT</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
      
          <artifactId>user-service</artifactId>
      
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
      
              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
              </dependency>
      
              <dependency>
                  <groupId>tk.mybatis</groupId>
                  <artifactId>mapper-spring-boot-starter</artifactId>
              </dependency>
      
              <!-- 引入eureka(註冊中心)-客戶端 -->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
              </dependency>
          </dependencies>
      
      </project>
      
    2. application.yml

      server:
        port: 9090
      spring:
        # 在eureka中註冊的服務名稱
        application:
          name: user-service
        # 數據庫連接信息配置
        datasource:
          url: jdbc:mysql://localhost:3306/yun6
          username: root
          password: root
          hikari:
            maximum-pool-size: 20
            minimum-idle: 10
      # 別名包
      mybatis:
        type-aliases-package: com.xiaoge.user.pojo
      
      # 註冊方
      # eureka配置 因爲它要去註冊中心註冊, 所以要配置
      eureka:
        client:
          service-url:
            defaultZone: http://127.0.0.1:10086/eureka, http://127.0.0.1:10087/eureka # 配置所有的eureka地址, 防止其中一個eureka掛掉
        instance:
          prefer-ip-address: true # 我希望使用ip地址
          ip-address: 127.0.0.1 # 設置ip地址
          lease-renewal-interval-in-seconds: 30 # 每隔30秒發一次心跳
          lease-expiration-duration-in-seconds: 90 # 每隔30秒發一次心跳, 如果隔了90秒都沒發, 那就證明掛了
      
  2. 啓動類

    1. UserApplication

      package com.xiaoge;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
      import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
      import tk.mybatis.spring.annotation.MapperScan;
      
      /**
       * @program: cloud-demo
       * @description: 服務的提供方
       * @author: Mr.Xiao
       * @create: 2020-05-04 15:43
       **/
      @EnableDiscoveryClient // 它也是客戶端, 它捷能兼容eureka 又能consul、zookeeper等等, 更通用, 更廣泛
      @SpringBootApplication
      @MapperScan("com.xiaoge.user.mapper")
      public class UserApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(UserApplication.class);
          }
      
      }
      
  3. 實體類

    1. User

      package com.xiaoge.user.pojo;
      
      import lombok.Data;
      import tk.mybatis.mapper.annotation.KeySql;
      
      import javax.persistence.Id;
      import javax.persistence.Table;
      import java.io.Serializable;
      import java.util.Date;
      
      /**
       * @program: cloud-demo
       * @description:
       * @author: Mr.Xiao
       * @create: 2020-05-04 15:46
       **/
      @Table(name = "tb_user")
      @Data
      public class User implements Serializable {
      
          @Id
          @KeySql(useGeneratedKeys = true) // id自動增長
          private Long id;
      
          // 用戶名
          private String username;
      
          // 密碼
          private String password;
      
          // 姓名
          private String name;
      
          // 年齡
          private Integer age;
      
          // 性別,1男性,2女性
          private Integer sex;
      
          // 出生日期
          private Date birthday;
      
          // 創建時間
          private Date created;
      
          // 更新時間
          private Date updated;
      
          // 備註
          private String note;
      
      }
      
  4. 表現層

    1. UserController

      package com.xiaoge.user.controller;
      
      import com.xiaoge.user.pojo.User;
      import com.xiaoge.user.service.UserService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      /**
       * @program: cloud-demo
       * @description:
       * @author: Mr.Xiao
       * @create: 2020-05-04 15:51
       **/
      @RestController
      @RequestMapping("/user")
      public class UserController {
      
          @Autowired
          private UserService userService;
      
          @GetMapping("/{id}")
          public User queryById(@PathVariable("id") Long id) {
              User user = userService.queryById(id);
              return user;
          }
      
      }
      
      
  5. 業務層

    1. UserService接口

      package com.xiaoge.user.service;
      
      import com.xiaoge.user.pojo.User;
      
      /**
       * @program: cloud-demo
       * @description:
       * @author: Mr.Xiao
       * @create: 2020-05-04 15:50
       **/
      public interface UserService {
      
          public User queryById(Long id);
      
      }
      
    2. UserServiceImpl實體類

      package com.xiaoge.user.service.impl;
      
      import com.xiaoge.user.mapper.UserMapper;
      import com.xiaoge.user.pojo.User;
      import com.xiaoge.user.service.UserService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      
      /**
       * @program: cloud-demo
       * @description:
       * @author: Mr.Xiao
       * @create: 2020-05-04 15:51
       **/
      @Service
      public class UserServiceImpl implements UserService {
      
          @Autowired
          private UserMapper userMapper;
      
          @Override
          public User queryById(Long id) {
              return userMapper.selectByPrimaryKey(id);
          }
      }
      
  6. Mapper

    1. UserMapper

      package com.xiaoge.user.mapper;
      
      
      import com.xiaoge.user.pojo.User;
      import tk.mybatis.mapper.common.Mapper;
      
      /**
       * @program: cloud-demo
       * @description:
       * @author: Mr.Xiao
       * @create: 2020-05-04 15:49
       **/
      
      public interface UserMapper extends Mapper<User> {
      }
      
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章