spring-cloud-eureka-consul-zookeeper注册中心入门案例

父项目

本案例为一个大项目下的几个模块,父项目只负责管理依赖版本控制

父项目pom文件

注意使用pom方式打包

<groupId>ganxie.xiaowen.cloudgroupId>
    <artifactId>springcloudartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>pompackaging>

    <modules>
        <module>cloud-provider-payment8001module>
        <module>cloud-consumer-order80module>
        <module>cloud-api-commonsmodule>
        <module>cloud-eureka-server7001module>
        <module>cloud-eureka-server7002module>
        <module>cloud-provider-payment8002module>
    modules>
    
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <junit.version>4.12junit.version>
        <log4j.version>1.2.17log4j.version>
        <lombok.version>1.16.18lombok.version>
        <mysql.version>8.0.17mysql.version>
        <druid.version>1.1.16druid.version>
        <mybatis.spring.boot.version>1.3.0mybatis.spring.boot.version>
    properties>

    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-project-info-reports-pluginartifactId>
                <version>3.0.0version>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-bootartifactId>
                <version>2.2.2.RELEASEversion>
                <type>pomtype>
                <scope>importscope>
            dependency>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>Hoxton.SR1version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                <version>2.1.0.RELEASEversion>
                <type>pomtype>
                <scope>importscope>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>${mysql.version}version>
                <scope>runtimescope>
            dependency>
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>${druid.version}version>
            dependency>
            <dependency>
                <groupId>org.mybatis.spring.bootgroupId>
                <artifactId>mybatis-spring-boot-starterartifactId>
                <version>${mybatis.spring.boot.version}version>
            dependency>
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>${junit.version}version>
            dependency>
            <dependency>
                <groupId>log4jgroupId>
                <artifactId>log4jartifactId>
                <version>${log4j.version}version>
            dependency>
        dependencies>
    dependencyManagement>

简介

入门案例分为四个模块,Eureka注册中心,服务提供者,服务消费者,公共资源模块,其中注册中心分别使用7001,7002端口模拟集群,服务提供者使用8001,8002端口模拟集群

公共资源模块

把服务提供者和服务消费者中相同的实体类提出到一个独立的模块,并分别引入pom依赖即可

pom

<dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.1.0version>
        dependency>
    dependencies>

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
     

    private Integer code;
    private String message;
    private T data;

    public CommonResult(Integer code, String message) {
     
        this.code = code;
        this.message = message;
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
     

    private Long id;
    private String serial;

}

EurekaServer7001(注册中心)

修改hosts文件

在末尾添加
127.0.0.1 eureka7001
127.0.0.1 eureka7002

pom

  <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
        dependency>

        
        <dependency>
            <groupId>ganxie.xiaowen.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
        dependency>
    dependencies>

配置文件(包含关闭自我保护机制)

server:
  port: 7001

eureka:
  instance:
    hostname: eureka7001  #eureka服务端的实例名字
  client:
    register-with-eureka: false    #表识不向注册中心注册自己
    fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      defaultZone: http://eureka7002:7002/eureka/
  #server:
    #关闭自我保护机制
    #enable-self-preservation: false
    #eviction-interval-timer-in-ms: 2000

主启动类

@SpringBootApplication
@EnableEurekaServer
public class Eureka7001 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(Eureka7001.class,args);
    }
}

EurekaServer7002(注册中心)

配置文件(包含关闭自我保护机制)

server:
  port: 7002

eureka:
  instance:
    hostname: eureka7002  #eureka服务端的实例名字
  client:
    register-with-eureka: false    #表识不向注册中心注册自己
    fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      defaultZone: http://eureka7001:7001/eureka/
  #server:
    #关闭自我保护机制
    #enable-self-preservation: false
    #eviction-interval-timer-in-ms: 2000

其他同上

EurekaClient8001(服务提供者)

pom

<dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.12version>
        dependency>
        <dependency>
            <groupId>ganxie.xiaowen.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
    dependencies>

配置文件(包含关闭自我保护机制)

server:
  port: 8001

spring:
  application:
    name: cloud-provider-payment #三个服务名称一致
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///cloud2020?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&userSSL=false
    username: root
    password: 1234

mybatis:
  type-aliases-package: ganxie.xiaowen.entity
  mapper-locations: classpath:mybatis/mapper/*.xml


eureka:
  client:
    #是否将自己注册金EurekaServer,默认是true
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001:7001/eureka/,http://eureka7002:7002/eureka/
  instance:
    instance-id: cloud-provider-payment8001
    prefer-ip-address: true
    #Eureka客户端想服务端发送心跳的时间间隔(默认三十秒)
    #lease-renewal-interval-in-seconds: 1
    #Eureka服务端在收到最后一次心跳后等待时间上线,单位为秒(默认是九十秒),超时将剔除服务
    #lease-expiration-duration-in-seconds: 2

主启动类

注意这里的注解是@EnableEurekaClient

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class Payment8001 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(Payment8001.class,args);
    }
}

服务(包含DiscoveryClient)

dao层和service层只是普通增查操作,不做演示
使用DiscoveryClient需要在主启动类上配置@EnableDiscoveryClient

@RestController
@Slf4j
public class PaymentController {
     

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment")
    public CommonResult create(@RequestBody Payment payment){
     
        int result = paymentService.create(payment);
        log.info("******插入结果:"+result);
        if (result>0) {
     
            return new CommonResult(200,"插入数据库成功,serverPort="+serverPort,result);
        }
        return new CommonResult(444,"插入数据库失败",null);
    }

    @GetMapping("/payment/{id}")
    public CommonResult selectById(@PathVariable("id") Long id){
     
        Payment payment = paymentService.selectPaymentById(id);
        log.info("******查询结果:"+payment);
        if (payment != null) {
     
            return new CommonResult(200,"查询成功,serverPort="+serverPort,payment);
        }
        return new CommonResult(444,"没有对应记录",null);
    }

    @GetMapping("/payment/discovery")
    public Object discoveryClient(){
     
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
     
            log.info("*********service:"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        for (ServiceInstance instance : instances) {
     
            log.info(instance.getServiceId()+"\t"+
                    instance.getHost()+"\t"+
                    instance.getPort()+"\t"+
                    instance.getUri());
        }
        return discoveryClient;
    }
}

EurekaClient8002(服务提供者)

除配置文件中端口为8002外完全同上

EurekaClient80(服务消费者)

pom

<dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        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>ganxie.xiaowen.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
    dependencies>

配置文件

server:
  port: 80
spring:
  application:
    name: cloud-order-service

eureka:
  client:
    #是否将自己注册金EurekaServer,默认是true,也可以不注册
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001:7001/eureka/,http://eureka7002:7002/eureka/

主启动类

@SpringBootApplication
@EnableEurekaClient
public class Order80 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(Order80.class,args);
    }
}

服务(使用ribbon实现负载均衡)

需要往容器中注入RestTemplate
@LoadBalanced 赋予restTemplate负载均衡的能力,默认算法为轮询算法,也可以自定义,接口为IRule

@Configuration
public class ApplicationContextConfig {
     

    @Bean
    @LoadBalanced //赋予restTemplate负载均衡的能力
    public RestTemplate myRestTemplate(){
     
        return new RestTemplate();
    }
}
@RestController
@Slf4j
public class OrderController {
     

//    private static final String PAYMENT_URL = "http://localhost:8001";
    private static final String PAYMENT_URL = "http://cloud-provider-payment";//服务提供者的spring.application.name

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
     
        return restTemplate.postForObject(PAYMENT_URL+"/payment",payment, CommonResult.class);
    }

    @GetMapping("consumer/payment/{id}")
    public CommonResult<Payment> selectPaymentById(@PathVariable("id") Long id){
     
        return restTemplate.getForObject(PAYMENT_URL+"/payment/"+id,CommonResult.class);
    }
}

Zookeeper8004(服务提供者)

pom

<dependencies>

        <dependency>
            <groupId>ganxie.xiaowen.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>


        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-zookeeper-discoveryartifactId>
            
            <exclusions>
                <exclusion>
                    <groupId>org.apache.zookeepergroupId>
                    <artifactId>zookeeperartifactId>
                exclusion>
            exclusions>
        dependency>
        
        
        <dependency>
            <groupId>org.apache.zookeepergroupId>
            <artifactId>zookeeperartifactId>
            <version>3.4.14version>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>


    dependencies>

配置文件

server:
  port: 8004
spring:
  application:
    name: cloud-provider-payment #三个服务名称一致
  cloud:
    zookeeper:
      connect-string: 192.168.188.172:2181

主启动类

@SpringBootApplication
@EnableDiscoveryClient //该注解用与向使用consul或者zookeeper作为注册中心时注册服务
public class Payment8004 {
     

    public static void main(String[] args) {
     
        SpringApplication.run(Payment8004.class,args);
    }
}

Zookeeper80(服务消费者)

pom

 <dependencies>

        <dependency>
            <groupId>ganxie.xiaowen.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>


        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-zookeeper-discoveryartifactId>
            
            <exclusions>
                <exclusion>
                    <groupId>org.apache.zookeepergroupId>
                    <artifactId>zookeeperartifactId>
                exclusion>
            exclusions>
        dependency>
        
        
        <dependency>
            <groupId>org.apache.zookeepergroupId>
            <artifactId>zookeeperartifactId>
            <version>3.4.14version>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>


    dependencies>

配置文件

server:
  port: 80
spring:
  application:
    name: cloud-consumer-order #三个服务名称一致
  cloud:
    zookeeper:
      connect-string: 192.168.188.172:2181

主启动类

@SpringBootApplication
@EnableDiscoveryClient
public class ZkOrder80 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(ZkOrder80.class,args);
    }
}

consul8006(服务提供者)

pom

<dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-consul-discoveryartifactId>
        dependency>

        <dependency>
            <groupId>ganxie.xiaowen.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>


        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>



    dependencies>

配置文件

server:
  port: 8006
spring:
  application:
    name: cloud-provider-payment #三个服务名称一致
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${
     spring.application.name}

主启动类

@SpringBootApplication
@EnableDiscoveryClient
public class Payment8006 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(Payment8006.class,args);
    }
}

consul80(服务消费者)

pom

 <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-consul-discoveryartifactId>
        dependency>

        <dependency>
            <groupId>ganxie.xiaowen.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>


        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>



    dependencies>

配置文件

server:
  port: 80
spring:
  application:
    name: cloud-consumer-order #三个服务名称一致
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${
     spring.application.name}

主启动类

@SpringBootApplication
@EnableDiscoveryClient
public class Consul80 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(Consul80.class,args);
    }
}

你可能感兴趣的:(spring-cloud-eureka-consul-zookeeper注册中心入门案例)