• Eureka集群和负载均衡


    Eureka集群和负载均衡

    #### 首先创建一个maven项目

    1.先删除掉src,然后只留pom.xml

    pom.xml

     <modules>
           <module>springcloud-api</module>
           <module>springcloud-provider-dept-8002</module>
           <module>springcloud-consumer-dept-80</module>
           <module>springcloud-eureka-7001</module>
           <module>springcloud-eurake-7002</module>
           <module>springcloud-eurake-7003</module>
           <module>springcloud-provider-dept-8003</module>
           <module>springcloud-provider-dept-8004</module>
           <module>springcloud-consumer-dept-feign</module>
           <module>springcloud-provider-dept-hystrix-8002</module>

       </modules>
       <!--打包方式-->
       <packaging>pom</packaging>
       <properties>
           <project.buile.sourceEncoding>UTF-8</project.buile.sourceEncoding>
           <maven-compiler-source>1.8</maven-compiler-source>
           <maven-compiler-target>1.8</maven-compiler-target>
           <junit.version>4.12</junit.version>
           <lombok.version>1.16.10</lombok.version>
           <log4j.version>1.2.17</log4j.version>
       </properties>
       <dependencyManagement>
           <dependencies>
               <!--springCloud的依赖-->
               <dependency>
                   <groupId>org.springframework.cloud</groupId>
                   <artifactId>spring-cloud-dependencies</artifactId>
                   <version>Greenwich.SR1</version>
                   <type>pom</type>
                   <scope>import</scope>
               </dependency>
               <!--springboot-->
               <dependency>
                   <groupId>org.springframework.boot</groupId>
                   <artifactId>spring-boot-dependencies</artifactId>
                   <version>2.1.4.RELEASE</version>
                   <type>pom</type>
                   <scope>import</scope>
               </dependency>
               <!--数据库的-->
               <dependency>
                   <groupId>mysql</groupId>
                   <artifactId>mysql-connector-java</artifactId>
                   <version>5.1.47</version>
               </dependency>
               <dependency>
                   <groupId>com.alibaba</groupId>
                   <artifactId>druid</artifactId>
                   <version>1.1.10</version>
               </dependency>
               <!--springboot启动器-->
               <dependency>
                   <groupId>org.mybatis.spring.boot</groupId>
                   <artifactId>mybatis-spring-boot-starter</artifactId>
                   <version>1.3.4</version>
               </dependency>
               <!--junit-->
               <dependency>
                   <groupId>junit</groupId>
                   <artifactId>junit</artifactId>
                   <version>${junit.version}</version>
               </dependency>
               <!--lombok-->
               <dependency>
                   <groupId>org.projectlombok</groupId>
                   <artifactId>lombok</artifactId>
                   <version>${lombok.version}</version>
               </dependency>
               <!--log4j-->
               <dependency>
                   <groupId>log4j</groupId>
                   <artifactId>log4j</artifactId>
                   <version>${log4j.version}</version>
               </dependency>
               <!--y用于日志和测试-->
               <dependency>
                   <groupId>ch.qos.logback</groupId>
                   <artifactId>logback-core</artifactId>
                   <version>1.2.3</version>
               </dependency>
           </dependencies>
       </dependencyManagement>
    </project>

    创建springcloud-api

    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>springcloud</artifactId>
           <groupId>com.liu</groupId>
           <version>1.0-SNAPSHOT</version>
       </parent>
       <modelVersion>4.0.0</modelVersion>

       <artifactId>springcloud-api</artifactId>
       <dependencies>
           <dependency>
               <groupId>org.projectlombok</groupId>
               <artifactId>lombok</artifactId>
           </dependency>
           <!--Feign做负载均衡时会在api里面加入fegin-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-feign</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>
       </dependencies>

    </project>

    创建Dept实体

    package com.example.pojo;

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.experimental.Accessors;

    import java.io.Serializable;
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public class Dept implements Serializable {// 实体类
       private Long deptno;
       private String dname;
       // 这个数据存储在那个数据库的字段,为服务,一个服务对应一个数据库,
       // 同一个信息可能存在不同的数据库
       private String db_source;

       public Dept(String dname) {
           this.dname = dname;
      }

    /*
       链式写法:
           Dept dept=new Dept();
           dept.setDeptNo(11).setDname('sss').setDb_source
    */
    }

    当Fegin做负载均衡时(会创建DeptClientService类进行接口传递)

    package com.example.service;

    import com.example.pojo.Dept;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;

    import java.util.List;

    @Component
    @FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
    public interface DeptClientService {

       @GetMapping("/dept/get/{id}")
       public Dept queryId(@PathVariable("id") Long id);

       @GetMapping("/dept/list")
       public List<Dept> queryAll();

       @PostMapping("/dept/add")
       public boolean addDept(Dept dept);

    }

     

    首先创建maven(springcloud-eureka-7001)

    pom.xml

    <dependencies>
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-eureka-server</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-devtools</artifactId>
           </dependency>
       </dependencies>

    application.yml

    server:
     port: 7001
    #Eureka配置
    eureka:
     instance:
       hostname: eureka7001.com #eureka服务端的实例名称
     client:
       register-with-eureka: false  #标识是否向服务端注册自己
       fetch-registry: false #如果为false,表示自己为注册中心
       service-url:  # 监控页面
         # 单机 defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
         # 集群(关联) defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
         defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

    启动类

    package com.example;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

    @SpringBootApplication
    @EnableEurekaServer // 启动之后访问http://localhost:7001
    public class EurekaService_7001 {
       public static void main(String args[]){
           SpringApplication.run(EurekaService_7001.class,args);
      }
    }

    创建maven(springcloud-eurake-7002)

    pom.xml和启动类和7001相同(启动类名称不能一样)

    server:
     port: 7002

    #Eureka配置
    eureka:
     instance:
       hostname: eureka7002.com #eureka服务端的实例名称
     client:
       register-with-eureka: false  #标识是否向服务端注册自己
       fetch-registry: false #如果为false,表示自己为注册中心
       service-url:  # 监控页面
         defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/

     

    创建maven(springcloud-eurake-70023

    pom.xml和启动类和7001相同(启动类名称不能一样)

    server:
     port: 7003

    #Eureka配置
    eureka:
     instance:
       hostname: eureka7003.com #eureka服务端的实例名称
     client:
       register-with-eureka: false  #标识是否向服务端注册自己
       fetch-registry: false #如果为false,表示自己为注册中心
       service-url:  # 监控页面
         defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

    创建maven(springcloud-provider-dept-8002)

    pom.xml

     <dependencies>
           <!--加入eureka依赖-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-eureka</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>
           <!--增加Eureka监控用的配置依赖-->
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-actuator</artifactId>
           </dependency>
           <dependency>
               <groupId>com.liu</groupId>
               <artifactId>springcloud-api</artifactId>
               <version>1.0-SNAPSHOT</version>
           </dependency>
           <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
           </dependency>
           <dependency>
               <groupId>mysql</groupId>
               <artifactId>mysql-connector-java</artifactId>
           </dependency>
           <dependency>
               <groupId>com.alibaba</groupId>
               <artifactId>druid</artifactId>
           </dependency>
           <dependency>
               <groupId>ch.qos.logback</groupId>
               <artifactId>logback-core</artifactId>
           </dependency>
           <dependency>
               <groupId>org.mybatis.spring.boot</groupId>
               <artifactId>mybatis-spring-boot-starter</artifactId>
           </dependency>
           <!--test-->
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-test</artifactId>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-jetty</artifactId>
           </dependency>
           <!--热部署工具-->
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-devtools</artifactId>
           </dependency>
       </dependencies>

    创建mapper

    package com.example.mapper;

    import com.example.pojo.Dept;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    import org.springframework.stereotype.Repository;

    import java.util.List;

    @Mapper
    @Repository
    public interface DeptMapper {
       @Insert(value = "insert into dept values(default,#{dept.dname},DATABASE())")
       public boolean addDept(@Param("dept") Dept dept);
       @Select("select * from dept where deptno=#{deptno}")
       public Dept queryById(@Param("deptno") Long id);
       @Select("select * from dept")
       public List<Dept> query();
    }

    创建service

    package com.example.service;

    import com.example.mapper.DeptMapper;
    import com.example.pojo.Dept;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import java.util.List;

    @Service
    public class DeptService {
       @Autowired
       private DeptMapper deptMapper;

       public boolean addDept(Dept dept) {
           return deptMapper.addDept(dept);
      }

       public Dept queryById(Long id) {
           return deptMapper.queryById(id);
      }

       public List<Dept> query() {
           return deptMapper.query();
      }
    }

    创建Controller

    package com.example.springcloud.controller;

    import com.example.pojo.Dept;
    import com.example.service.DeptService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.client.ServiceInstance;
    import org.springframework.cloud.client.discovery.DiscoveryClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;

    import java.util.List;

    @RestController
    public class DeptController {
       @Autowired
       private DeptService deptService;

       // 获取 一些配置信息,得到具体的微服务
       @Autowired
       private DiscoveryClient discoveryClient;

       @PostMapping("/dept/add")
       public boolean addDept(Dept dept) {
           return deptService.addDept(dept);

      }

       @GetMapping("/dept/get/{id}")
       public Dept get(@PathVariable("id") Long id) {
           Dept dept = deptService.queryById(id);
           if(dept==null){
               throw new RuntimeException("fail Please check you Code");
          }
           return dept;

      }

       @GetMapping("/dept/list")
       public List<Dept> addDept() {
           return deptService.query();

      }

       // 注册进来的微服务,获取一些信息‘ 这方法并非是业务代码,只是显示微服务的接口信息
       @GetMapping("/dept/discovery")
       public Object discovery() {
           // 获取到服务的列表清单
           List<String> services = discoveryClient.getServices();
           System.out.println("discovery=>services:" + services);

           List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
           for (ServiceInstance instance : instances) {
               System.out.println(
                       instance.getHost() + " " +
                               instance.getPort() + " " +
                               instance.getUri() + " " +
                               instance.getServiceId()
              );
          }
           return this.discoveryClient;
      }
    }

    启动类

    package com.example;

    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;

    @SpringBootApplication
    @EnableEurekaClient // 在服务开启之后会自动注册到eureka中
    @EnableDiscoveryClient // 服务发现·
    public class DeptProvider_8002 {
       public static void main(String args[]) {
           SpringApplication.run(DeptProvider_8002.class, args);
      }
    }

    application.yml配置

    server:
     port: 8002
    spring:
     application:
       name: springcloud-provider-dept
     datasource:
       url: jdbc:mysql://localhost:3306/mytest?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
       username: root
       password: root
       driver-class-name: com.mysql.jdbc.Driver
       type: com.alibaba.druid.pool.DruidDataSource
    mybatis:
     # model的包
     type-aliases-package: com.example.pojo
     configuration:
    #    开启驼峰uName自动映射到u_name
         map-underscore-to-camel-case: true

    # eureka的配置
    eureka:
     client:
       service-url:
         defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/,http://localhost:7003/eureka/
     instance:
       instance-id: springcloud-provider-dept-8002
       prefer-ip-address: true # true可以显示服务的IP地址

    # info 配置
    info:
     app.name: liuli-springcloud
     company.name: baidu.com

    如果需要创建多个负责均衡的话,则创建的maven项目和springcloud-provider-dept-8002相似,不过需要改端口号,数据库名,instance-id:

    =======================================================================================

    创建消费客户端maven(springcloud-consumer-dept-80)(带有Ribbon负载均衡)

    pom.xml

     <build>
           <plugins>
               <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <configuration>
                       <source>7</source>
                       <target>7</target>
                   </configuration>
               </plugin>
           </plugins>
       </build>

       <!--实体类+web-->
       <dependencies>
           <!--Ribbon-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-ribbon</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>
           <!--Eurake-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-eureka</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>

           <dependency>
               <groupId>com.liu</groupId>
               <artifactId>springcloud-api</artifactId>
               <version>1.0-SNAPSHOT</version>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-devtools</artifactId>
           </dependency>
       </dependencies>

    application.yml

    server:
     port: 80

    #Eurake配置
    eureka:
     client:
       register-with-eureka: false # 不向eurake注册自己
       service-url:
         defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

    创建DeptConsumerController

    package com.example.springcloud.controller;

    import com.example.pojo.Dept;
    import org.springframework.beans.factory.annotation.Autowired;
    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;

    @RestController
    public class DeptConsumerController {


       @Autowired
       private RestTemplate restTemplate;

       // Ribbon 我们这里的地址,应该是一个变量,通过服务者来访问
    //   private static final String REST_URL_PREFIX="http://localhost:8002";
       private static final String REST_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT";

       @RequestMapping("/consumer/dept/get/{id}")
       public Dept get(@PathVariable("id")Long id){
           return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class);
      }
       @RequestMapping("/consumer/dept/add")
       public boolean add(Dept dept){
           System.out.println("客户端的信息=>"+dept);
           return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add?",dept,Boolean.class);
      }
       @RequestMapping("/consumer/dept/list")
       public List<Dept> get(){
           return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class);
      }
    }

    创建config配置类

    package com.example.springcloud.config;

    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;

    @Configuration
    public class ConfigBean {
       // 配置负载均衡实现RestTemplate
       @Bean
       @LoadBalanced // Ribbon
       public RestTemplate getRestTemplate(){
           return  new RestTemplate();
      }

    }

    创建Ribbon负载均衡类(tip:这个类的位置不可以和启动类同级,放在启动类的上一级目录)

    package com.example.myrule;

    import com.netflix.loadbalancer.IRule;
    import com.netflix.loadbalancer.RandomRule;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    public class RibbonRuleDemo {
       @Bean
       public IRule myRule() {
           return new RandomRule();
      }
    }

    启动类

    package com.example.springcloud;

    import com.example.myrule.RibbonRuleDemo;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    import org.springframework.cloud.netflix.ribbon.RibbonClient;

    // Ribbon 和 Eureka整合以后,客户端可以直接调用
    @SpringBootApplication
    @EnableEurekaClient
    @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = RibbonRuleDemo.class)
    public class DeptConsumer_80 {
    public  static void main(String args[]){
       SpringApplication.run(DeptConsumer_80.class,args);
    }
    }

    Fegin做负载均衡时

    创建maven项目(springcloud-consumer-dept-feign)

    <?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>springcloud</artifactId>
           <groupId>com.liu</groupId>
           <version>1.0-SNAPSHOT</version>
       </parent>
       <modelVersion>4.0.0</modelVersion>

       <artifactId>springcloud-consumer-dept-feign</artifactId>
       <!--实体类+web-->
       <dependencies>
           <!--Feign-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-feign</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>
           <!--Ribbon-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-ribbon</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>
           <!--Eurake-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-eureka</artifactId>
               <version>1.4.6.RELEASE</version>
           </dependency>

           <dependency>
               <groupId>com.liu</groupId>
               <artifactId>springcloud-api</artifactId>
               <version>1.0-SNAPSHOT</version>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-devtools</artifactId>
           </dependency>
       </dependencies>

    </project>

    application.yml

    server:
     port: 80

    #Eurake配置
    eureka:
     client:
       register-with-eureka: false # 不向eurake注册自己
       service-url:
         defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

    创建config配置类

    package com.example.springcloud.config;

    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;

    @Configuration
    public class ConfigBean {
       // 配置负载均衡实现RestTemplate
       @Bean
       @LoadBalanced // Ribbon
       public RestTemplate getRestTemplate(){
           return  new RestTemplate();
      }


    }

    创建controller类(DeptConsumerController)

    package com.example.springcloud.controller;

    import com.example.pojo.Dept;
    import com.example.service.DeptClientService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    import java.util.List;

    @RestController
    public class DeptConsumerController {


       @Autowired
       private DeptClientService deptClientService;

       @RequestMapping("/consumer/dept/get/{id}")
       public Dept get(@PathVariable("id") Long id) {
           return deptClientService.queryId(id);
      }

       @RequestMapping("/consumer/dept/add")
       public boolean add(Dept dept) {
           return deptClientService.addDept(dept);
      }

       @RequestMapping("/consumer/dept/list")
       public List<Dept> get() {
           return deptClientService.queryAll();
      }
    }

    启动类

    package com.example.springcloud;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    import org.springframework.context.annotation.ComponentScan;

    // Ribbon 和 Eureka整合以后,客户端可以直接调用
    @SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients(basePackages = "com.example")
    @ComponentScan("com.example")
    public class FeignDeptConsumer_80 {
    public  static void main(String args[]){
       SpringApplication.run(FeignDeptConsumer_80.class,args);
    }
    }

     

  • 相关阅读:
    scala-class
    uva-10422-骑士-搜索题
    HDU 5724
    HDU 5728
    CodeForces 414B
    CodeForces 698A
    Codeforces Round #363 (Div. 2)
    BestCoder 2nd Anniversary 1001 Oracle
    BestCoder 2nd Anniversary 1002 Arrange
    HDU 4798
  • 原文地址:https://www.cnblogs.com/liuli-warriors/p/12669026.html
Copyright © 2020-2023  润新知