Eureka、Zookeeper、Consul

139 阅读5分钟

Boot 和 cloud 对应版本的查看方法

官网查看:

图片.png

详细查看:start.spring.io/actuator/in…

Eureka基础知识,服务治理,spring-cloud封装了NetFlix公司开发的Eureka来实现服务治理,在传统的rpc远程调用框架中管理每个服务与服务之间依赖关系比较复杂、管理复杂、所以需要服务治理、管理服务与服务之间的关系依赖,可以实现服务调用,负载均衡,容错,实现服务发现与注册。

服务注册与发现:Eureka采用的是c/s架构的设计,Eureka Server作为服务注册功能的服务器,它是服务注册中心。系统中的其他微服务,使用Eureka Client连接到Eureka Server 并维持心跳。系统维护人员可以通过Eureka Server 来监控系统中的微服务是否正常。 在服务注册发现中,有一个注册中心,服务启动时候,会把自己的服务器信息,例如服务通信地址以别名的方式注册在注册中心上。另外一方,以该别名的方式去注册中心上获取到实际的服务通信地址,然后在实现rpc调用rpc远程调用框架核心设计思想,在于注册中心,因为使用注册中心管理每一个服务与服务之间的一个依赖关系,在任何一个远程rpc框架中都会有一个注册中心(用来存放服务地址相关信息)

图片.png

图片.png

Eureka包含两个组件:Eureka Server和Eureka Client

Eureka Server提供服务注册服务 各个节点启动后,会在EurekaServer中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到

EurekaClient是一个Java客户端,用于简化Eureka Server的交互,客户端同时也具备一个内置的、使用轮询(round-robin)负载算法的负载均衡器。在应用启动后,将会向Eureka Server发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将会从服务注册表中把这个服务节点移除(默认90秒)

父工程POM

<?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.nyc.cloud</groupId>
    <artifactId>springcloud2020</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>cloud-provider-payment8001</module>
    </modules>

    <packaging>pom</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.complier.target>1.8</maven.complier.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.14</log4j.version>
        <lombok.version>1.16.18</lombok.version>
        <!--<mysql.version>5.1.47</mysql.version>-->
        <mysql.version>8.0.12</mysql.version>
        <druid.version>1.1.16</druid.version>
        <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
    </properties>


    <dependencyManagement>
        <dependencies>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.2.4.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.2.2.RELEASE</version>
            </dependency>
            <!--spring boot 2.2.2.RELEASE-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!--spring cloud-->
<!--            <dependency>-->
<!--                <groupId>org.springframework.cloud</groupId>-->
<!--                <artifactId>spring-cloud-build-dependencies</artifactId>-->
<!--                <version>Hoxton.SR1</version>-->
<!--                <type>pom</type>-->
<!--                <scope>import</scope>-->
<!--            </dependency>-->

            <!--springCloud alibaba 2.1.0.RELEASE-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>

            <!--druid-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>

            <!--springBoot-mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!--热部署插件-->

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

开发环境种开启热部署

添加如下配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

全部打上对勾

图片.png

按下ctrl + shift + alt + /

图片.png

勾选如下配置即可

图片.png

首先整个项目中的共用模块cloud-api-commons

pom

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

    <!-- spring-boot-devtools -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <version>2.7.2</version>
    </dependency>

    

    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <!--<scope>provided</scope>-->
    </dependency>

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

实体类 Payment

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Payment {
    private Long id;
    private String serial;
}

公用返回结果 CommonResult<T>

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult<T> {
    private Integer code;
    private String message;
    private T data;

    public CommonResult(Integer code,String message){
        this(code,message,null);
    }
}

创建Eureka服务中心模块cloud-eureka-server7001

POM

<dependencies>
    <dependency>
        <groupId>com.nyc.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <artifactId>cloud-api-commons</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
    </dependency>

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


    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>
</dependencies>

yml配置

server:
  port: 7001

eureka:
  instance:
    hostname: localhost #eureka 服务端的实例名称
    #hostname: localhost
  client:
    #false 表示不向注册中心注册自己
    register-with-eureka: false
    #false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索事务
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

启动类

不要忘记@EnableEurekaServer注解

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

启动测试访问http://localhost:7001

图片.png

创建支付服务模块子工程 cloud-provider-payment8001

pom

    <dependencies>
        <!--Eureka 客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.nyc.cloud</groupId>
            <version>1.0-SNAPSHOT</version>
            <artifactId>cloud-api-commons</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.13</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>org.springframework.cloud</groupId>-->
<!--            <artifactId>spring-cloud-build-dependencies</artifactId>-->
<!--            <version>Hoxton.SR1</version>-->
<!--            <type>pom</type>-->
<!--            <scope>import</scope>-->
<!--        </dependency>-->

        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <!--Eureka的服务端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>2.2.1.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.dataformat</groupId>
                    <artifactId>jackson-dataformat-xml</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

写yml配置

server:
  port: 8001

#注册到Eureka
eureka:
  client:
    #false 表示不向注册中心注册自己
    register-with-eureka: true
    #false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索事务
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka/
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost/db2019?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  application:
    name: cloud-payment-service

#mybatis 映射文件
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.nyc.eurekaserver.entity

dao

@Mapper
public interface PaymentDao {

    public int create(Payment payment);

    public Payment getPaymentById(@Param("id") Long id);
}

mapper

<mapper namespace="com.nyc.eurekaserver.dao.PaymentDao">
    <insert id="create" parameterType="com.nyc.eurekaserver.entity.Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment(serial) values(#{serial})
    </insert>

    <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
        select * from payment where id=#{id}
    </select>

    <resultMap id="BaseResultMap" type="com.nyc.eurekaserver.entity.Payment">
        <id column="id" property="id" jdbcType="BIGINT"></id>
        <id column="serial" property="serial" jdbcType="VARCHAR"></id>
    </resultMap>
</mapper>

service

package com.nyc.eurekaserver.service;
import com.nyc.eurekaserver.entity.Payment;

public interface PaymentService {
    public int create(Payment payment);
    public Payment getPaymentById(Long id);
}
package com.nyc.eurekaserver.service.impl;

import com.nyc.eurekaserver.dao.PaymentDao;
import com.nyc.eurekaserver.entity.Payment;
import com.nyc.eurekaserver.service.PaymentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class PaymentImpl implements PaymentService {


    @Resource
    private PaymentDao paymentDao;

    @Override
    public int create(Payment payment) {
        return paymentDao.create(payment);
    }

    @Override
    public Payment getPaymentById(Long id) {
        return paymentDao.getPaymentById(id);
    }
}

controller

package com.nyc.eurekaserver.controller;


import com.nyc.eurekaserver.entity.CommonResult;
import com.nyc.eurekaserver.entity.Payment;
import com.nyc.eurekaserver.service.PaymentService;
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.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController

public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @PostMapping("/payment/save")
    public CommonResult create(Payment payment){
        int result = paymentService.create(payment);
        if (result > 0){
            return new CommonResult<>(200,"插入数据库成功",result);
        }
        return new CommonResult<>(400,"插入数据库失败",null);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment result = paymentService.getPaymentById(id);
        if (result !=null){
            return new CommonResult<>(200,"查询成功",result);
        }
        return new CommonResult<>(400,"查询失败",null);
    }
}

启动类

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

创建消费者服务子模块cloud-consumer-order80

pom

<dependencies>
    <!--Eureka 客户端-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>com.nyc.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <artifactId>cloud-api-commons</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
    </dependency>

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

写配置yml

server:
  port: 80


spring:
  application:
    name: cloud-order-service

eureka:
  client:
    #false 表示不向注册中心注册自己
    register-with-eureka: true
    #false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索事务
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka/

config

@Configuration
public class ApplicationContextConfig {


    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

controller

package com.nyc.eurekaclient.controller;

import com.nyc.eurekaclient.entity.CommonResult;
import com.nyc.eurekaclient.entity.Payment;
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.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {


    public static final String PAYMENT_URL = "http://localhost:8001";

    @Autowired
    private RestTemplate restTemplate;


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


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

启动类

@EnableEurekaClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class);
    }
}

提供方模块8001,消费方80注册到eureka服务中心

pom

<!--Eureka 客户端-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>

yml配置

eureka:
  client:
    #false 表示不向注册中心注册自己
    register-with-eureka: true
    #false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索事务
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka/

启动类上标注 @EnableEurekaClient

图片.png

测试http://localhost/consumer/payment/get/1

图片.png

Eureka 集群环境搭建

在本地配置文件中添加如下配置C:\Windows\System32\drivers\etc\hosts

图片.png

创建另外一个服务模块 cloud-eureka-server7002

这个模块除了yml配置文件不一样,剩下的和7001模块是一摸一样的

yml

这是7002要注册到7001了,7001同理要注册进入7002

server:
  port: 7002

# 集群版
eureka:
  instance:
    hostname: eureka7002.com
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/

图片.png

图片.png

将服务提供模块8001和服务消费模块80注册到集群当中

只需要修改yml配置

eureka:
  client:
    #是否要将自己入驻到EurekaServer 默认为 true
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true,单节点无所谓,集群必须设置ture才能配合ribbon使用负载均衡
    fetch-registry: true
    service-url:
      #defaultZone: http://localhost:7001/eureka   单机版
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

在8001 和 8002 服务提供方上分别获取端口信息

@RestController
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

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

    @PostMapping("/payment/save")
    public CommonResult create(Payment payment){
        int result = paymentService.create(payment);
        if (result > 0){
            return new CommonResult<>(200,"插入数据库成功 , 端口是:" + serverport,result);
        }
        return new CommonResult<>(400,"插入数据库失败",null);
    }
    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment result = paymentService.getPaymentById(id);
        if (result !=null){
            return new CommonResult<>(200,"查询成功 , 端口是:" + serverport,result);
        }
        return new CommonResult<>(400,"查询失败",null);
    }
}

在80 服务消费端url修改成如下内容

public static final String PAYMENT_URL = "http://cloud-payment-service";

访问:http://localhost/consumer/payment/get/1

图片.png

eureka 的自我保护机制

如图显示的内容证明eureka进入了自我保护机制。如果进入自我保护机制,Eureka Serve将会尝试保护其服务注册表中的信息,不会删除服务注册表中的信息,也就是不会注销任何的微服务

图片.png

eureka 关闭自我保护

Eureka 服务端 7001

eureka:
  instance:
    hostname: eureka7001.com
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone:  http://eureka7001.com:7001/eureka/   # 单机版

  server:
    enable-self-preservation: true #默认是true 开启自我保护模式
    eviction-interval-timer-in-ms: 2000 #单位毫秒

Eureka服务提供方 8001

eureka:
  client:
    #false 表示不向注册中心注册自己
    register-with-eureka: true
    #false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索事务
    fetch-registry: true
    service-url:
     # defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/ 集群版本
      defaultZone: http://localhost:7001/eureka
  instance:
    instance-id: payment8001
    prefer-ip-address: true
    #Eureka 客户端向服务端发送心跳的时间间隔,默认是30秒
    lease-renewal-interval-in-seconds: 2
    #Eureka 服务器端在收到最后一次心跳后等待时间上限,默认是90秒,超时就会删除
    lease-expiration-duration-in-seconds: 3

图片.png

Zookeeper

在centos7上安装 Zookeeper

首先在apache官网上下载Zookeeper安装包,通过传输工具传到centos上并解压

图片.png

将解压后的安装包目录中的conf下的zoo_sample.cfg文件复制一份,改名为zoo.cfg

图片.png

启动zookeeper

sh bin/zkServer.sh start

图片.png

查看zookeeper的状态

sh bin/zkServer.sh status

图片.png

使用客户端连接zookeeper

sh bin/zkCli.sh 

关闭zookeeper

sh bin/zkServer.sh stop

图片.png

创建模块 服务提供模块 cloud-provider-payment8004 ,消费模块cloud-consumerzk-order80

服务提供模块 cloud-provider-payment8004

pom

<dependencies>
    <!-- zookeeper -->
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.8.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        <version>2.2.2.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.zookeeper</groupId>
                <artifactId>zookeeper</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>com.nyc.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <artifactId>cloud-api-commons</artifactId>
    </dependency>


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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>


    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.13</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
</dependencies>

yml

#端口
server:
  port: 8004

#注册进入zookeeper
spring:
  cloud:
    zookeeper:
      connect-string: 192.168.216.100:2181
  application:
    name: cloud-payment-service

  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost/db2019?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.nyc.eurekaserver.entity

controller

@RestController
public class PaymentController {

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

    @GetMapping(value = "/payment/zk")
    public String paymentZk(){
        return "springcloud with zookeeper: " + serverPort + "\t" + UUID.randomUUID().toString();
    }
}

启动类

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

消费模块cloud-consumerzk-order80

POM

<dependencies>
    <!-- zookeeper -->
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.8.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        <version>2.2.2.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.zookeeper</groupId>
                <artifactId>zookeeper</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>com.nyc.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <artifactId>cloud-api-commons</artifactId>
    </dependency>


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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>


    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.13</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
</dependencies>

YML

#端口
server:
  port: 80

#注册进入zookeeper
spring:
  cloud:
    zookeeper:
      connect-string: 192.168.216.100:2181
  application:
    name: cloud-order-consumer

  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost/db2019?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.nyc.eurekaserver.entity

controller

package com.nyc.zookeeper.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class OrderZKController {

    public static final String INVOKE_URL = "http://cloud-payment-service";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consume/payment/zk")
    public String paymentInfo(){
        String result = restTemplate.getForObject(INVOKE_URL+"/payment/zk",String.class);
        return result;
    }
}

config

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

启动类

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

连接到ZK的客户端

图片.png

Consul

Consul 官网下载Consul

启动命令 consul agent -dev

图片.png

创建服务提供模块cloud-providerconsul-payment8006

pom

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

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

    <dependency>
        <groupId>com.nyc.cloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>
</dependencies>

yml

server:
  port: 8006

spring:
  application:
    name: consul-provider-payment
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

controll

@RestController
public class PaymentController {

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

    @GetMapping("/payment/consul")
    public String paymentConsul(){
        return "spring-cloud with consul: " + serverPort + "\t" + UUID.randomUUID();

    }
}

启动类

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

创建服务消费模块 cloud-consumerconsul-order80

pom

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

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

    <dependency>
        <groupId>com.nyc.cloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>
</dependencies>

yml

server:
  port: 80

spring:
  application:
    name: consul-consume-order
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

config

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

controller

@RestController
public class OrderConsulController {

    public static final String INVOKE_URL = "http://consul-provider-payment";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping(value = "/consumer/payment/consul")
    public String paymentInfo(){
        String result =  restTemplate.getForObject(INVOKE_URL+"/payment/consul",String.class);
        return result;
    }
}

启动类

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

在consul面板上可以看到这两个服务已经被注册进去了

图片.png

CAP理论

C (Consistency 强一致性)

A(Availabliity 可用性)

P(Partition tolerance 分区容错性)

Eureka 是 AP / zookeeper,consul 属于(CP)