后端之路

springCloud --- 初级篇(1)

2020-06-07  本文已影响0人  贪挽懒月

本系列笔记涉及到的代码在GitHub上,地址:https://github.com/zsllsz/cloud

本文涉及知识点:

一、什么是springCloud?

1、springCloud介绍:

2、springCloud中的常用技术:
springCloud全家桶中我们常用的技术有如下几种:

3、技术选型:
springCloud这么多技术,每种技术的版本如何选择?可以访问https://start.spring.io/actuator/info,会返回一个json串,里面会说明springCloud版本与其他各技术的版本支持。本文涉及到的项目各技术版本如下:

二、项目搭建

1、 新建父工程:
新建一个maven聚合工程,名为cloud,然后在pom.xml中定义一些依赖的版本。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.zhu.springCloud</groupId>
    <artifactId>cloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!-- 表示该工程是一个父工程 -->
    <packaging>pom</packaging>

    <name>Maven</name>
    <url>http://maven.apache.org/</url>
    <inceptionYear>2001</inceptionYear>

    <!--统一管理jar包版本 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>12</maven.compiler.source>
        <maven.compiler.target>12</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <lombok.version>1.18.10</lombok.version>
        <log4j.version>1.2.17</log4j.version>
        <mysql.version>5.1.47</mysql.version>
        <druid.version>1.1.16</druid.version>
        <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
    </properties>

    <!--子模块继承之后,提供作用:锁定版本+子module不用写groupId和version -->
    <!-- 只是声明依赖,不会引入具体依赖 -->
    <dependencyManagement><!--定义规范,但不导入 -->
        <dependencies>
            <dependency>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>3.0.0</version>
            </dependency>
            <!--spring boot 2.2.2 -->
            <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 Hoxton.SR1 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud 阿里巴巴 -->
            <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>
                <scope>runtime</scope>
            </dependency>
            <!-- druid -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <!--mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.version}</version>
            </dependency>
            <!--junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <!--log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.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>

父工程就是这样,只有个pom文件。

2、新建数据库:
数据库只有一张表,如下:

payment表

3、在父工程下新建名为cloud-api-commons的moudle,定义一些公用的类:

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zhu.springCloud</groupId>
        <artifactId>cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>cloud-api-commons</artifactId>

    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 糊涂工具包 -->
        <dependency>
          <groupId>cn.hutool</groupId>
          <artifactId>hutool-all</artifactId>
          <version>5.1.0</version>
        </dependency>
    </dependencies>
</project>
package com.zhusl.springcloud.entities;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {

    private static final long serialVersionUID = 1L;
    
    private Long id;
    private String serial;
}
package com.zhusl.springcloud.common;
import lombok.Data;
@Data
public class JsonResult<T> {
    private Integer code;
    private String message;
    private T data;
    public JsonResult(Integer code, String message) {
        this(code, message, null);
    }
    public JsonResult(Integer code, String message, T data) {
        super();
        this.code = code;
        this.message = message;
        this.data = data;
    }
    public JsonResult() {
        super();
    }
}

然后这个通用工程也就完成了,将其maven install一下。

4、在父工程下新建名为cloud-provider-payment8001的moudle,充当支付服务:

<?xml version="1.0"?>
<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>
    <parent>
        <groupId>com.zhu.springCloud</groupId>
        <artifactId>cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>cloud-provider-payment8001</artifactId>
    <dependencies>
        <dependency>
            <groupId>com.zhu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</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.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>
server:
  port: 8001

spring:
  application:
    name: cloud-payment-service #提交到注册中心的微服务名称
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/db2020?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123
    
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.zhusl.springcloud.entities
@SpringBootApplication
public class PaymentMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8001.class, args);
    }
}
@Mapper
public interface PaymentDao {
    public int create(Payment payment);
    public Payment getPaymentById(@Param("id") Long id);
}

mapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhusl.springcloud.dao.PaymentDao">
   <resultMap type="com.zhusl.springcloud.entities.Payment" id="PaymentMap">
      <id column="id" property="id" jdbcType="BIGINT"/>
      <result column="serial" property="serial" jdbcType="VARCHAR"/>
   </resultMap>
   <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
      insert into payment(serial) values(#{serial});
   </insert>
   <select id="getPaymentById" parameterType="Long" resultMap="PaymentMap">
      select * from payment where id=#{id};
   </select>
</mapper>

service:

@Service
public class PaymentServiceImpl implements PaymentService {
    @Autowired
    private PaymentDao paymentDao;
    @Override
    public int create(Payment payment) {
        return paymentDao.create(payment);
    }
    @Override
    public Payment getPaymentById(Long id) {
        return paymentDao.getPaymentById(id);
    }
}

controller:

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @PostMapping("/create")
    public JsonResult<Payment> create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("========插入结果:=========" + result);
        if (result > 0) {
            return new JsonResult<Payment>(200, "success", null);
        } else {
            return new JsonResult<Payment>(400, "fail", null);
        }
    }

    @GetMapping("/{id}")
    public JsonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("======== 执行操作==========");
        if (payment != null) {
            return new JsonResult<Payment>(200, "success", payment);
        } else {
            return new JsonResult<Payment>(400, "fail", null);
        }
    }
}

这样就搭完了payment服务。

5、在父工程下新建名为cloud-consumer-order80的moudle,充当订单服务:

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zhu.springCloud</groupId>
        <artifactId>cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>cloud-consumer.order80</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.zhu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <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-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>
server:
  port: 80

spring:
  application:
    name: cloud-order-service #提交到注册中心的微服务名称
@SpringBootApplication
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class, args);
    }
}
@Configuration
public class ApplicationConfig {
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}
@RestController
@RequestMapping("/consumer")
public class OrderController {
    private static final String PAYMENT_URL = "http://localhost:8001";
    @Autowired
    private RestTemplate restTemplate;

    @SuppressWarnings("unchecked")
    @GetMapping("/payment/create")
    public JsonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, JsonResult.class);
    }
    
    @SuppressWarnings("unchecked")
    @GetMapping("/payment/get/{id}")
    public JsonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, JsonResult.class);
    }
}

这里直接写payment服务所在的服务器ip和端口,然后通过Spring的restTemplate直接发送post或者get请求,从而达到服务相互调用的目的。有人说,这样就已经达到目的了,服务在不同的服务器,也能相互调用,为什么还要学其他的呢?因为,这样调用不好做服务的协调与管理。需要一个中间商,来维护管理这些服务,做服务的注册与发现。springCloud支持的中间商有很多,如开篇说的eureka、zookeeper和nacos。

三、服务的注册与发现之eureka

eureka虽然停更了,但还是可以了解一下。eureka中有两个概念,一个server和一个client。server是提供服务注册功能的,也就是我们的服务就注册到server中;client可以理解为就是我们需要注册的服务。显然上面的payment8001和order80是我们需要注册的服务。eureka server中存的其实就是一些kv键值对,key是服务的名称,value是服务的调用地址。

1、在父工程下新建名为cloud-eureka-server7001的moudle,作为eureka的server:

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zhu.springCloud</groupId>
        <artifactId>cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>cloud-eureka-server7001</artifactId>
    <name>cloud-eureka-server7001</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- eureka server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.zhu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <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-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>
server:
  port: 7001

eureka:
  instance:
    hostname: localhost #eureka服务端的实例名称
  client:
    register-with-eureka: false # false表示不向服务中心注册自己
    fetch-registry: false # false表示自己就是注册中心,维护服务实例,而不去检索服务
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # 向eureka查询和注册服务都通过这个地址
@SpringBootApplication
@EnableEurekaServer // 表明这个项目是eureka注册中心
public class EurekaMain7001 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaMain7001.class, args);
    }
}

然后启动这个项目,访问localhost:7001,可以看到如下画面:

eureka

这仅仅是将注册中心eureka的server搭建好了,但是我们并没有把服务注册进去,接下来我们把payment8001注册进eureka中。

2、将payment8001注册进eureka中:

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
eureka:
  client:
    register-with-eureka: true # 将自己注册进eureka
    fetch-registry: true # 从eureka抓取自己的注册信息
    service-url:
      defaultZone: http://localhost:7001/eureka   #eureka server所在的主机和端口
@EnableEurekaClient

这样就行了,启动payment8001,再刷新localhost:7001,就会发现eureka中有payment8001这个服务了,如下图:

服务注册成功

3、将order80注册进eureka:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
eureka:
  client:
    register-with-eureka: true # 将自己注册进eureka,不注册就false
    fetch-registry: true # 从eureka抓取自己的注册信息
    service-url:
      defaultZone: http://localhost:7001/eureka/ #eureka server所在的主机和端口
@EnableEurekaClient
private static final String PAYMENT_URL = "http://localhost:8001";

换成

private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
服务注册成功 成功调用服务

4、eureka集群:
eureka集群原理就是互相注册,对外表现为一个整体。上面新建了一个cloud-eureka-server7001,端口是7001,现在再建一个名为cloud-eureka-server7002的module,端口为7002。

127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
server:
  port: 7001
# 集群的写法
eureka:
  instance:
    hostname: eureka7001.com #eureka服务端的实例名称
  client:
    register-with-eureka: false # false表示不向服务中心注册自己
    fetch-registry: false # false表示自己就是注册中心,维护服务实例,而不去检索服务
    service-url:
      defaultZone: http://eureka7002.com:7002/eureka/ # 把自己注册到7002中,如果还有7003、7004,则用逗号隔开即可
  server:
    enable-self-preservation: false #关闭自我保护
    eviction-interval-timer-in-ms: 2000 #检测心跳的时间间隔
server:
  port: 7002
  
# 集群的写法
eureka:
  instance:
    hostname: eureka7002.com #eureka服务端的实例名称
  client:
    register-with-eureka: false # false表示不向服务中心注册自己
    fetch-registry: false # false表示自己就是注册中心,维护服务实例,而不去检索服务
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/ # 把自己注册到7001,若是集群有三个以上,那么此行的多个url之间用逗号隔开即可
  server:
    enable-self-preservation: false #关闭自我保护
    eviction-interval-timer-in-ms: 2000 #检测心跳的时间间隔

其他的都和7001一样即可,这样就完成eureka集群了。

把原先的

defaultZone: http://localhost:7001/eureka/

替换成

defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
eureka集群成功

5、payment服务集群:

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

@LoadBalanced注解可以理解为轮询,就是一人一次。

第一次访问
第二次访问

可以看到,第一次调用的是payment8001,第二次调用的是payment8002,集群成功了。如果你多次调用的都是同一个,很有可能是缓存原因,解决办法我在nginx一文中讲过。

6、status配置:

status

在status这里,还显示了localhost,不想对外显示localhost,并且当我把鼠标悬停在cloud-order-service:80,我要显示服务所在的主机的IP。那么只需要在order80项目的yml加上如下配置即可:

instance: #和client对齐
    instance-id: order80
    prefer-ip-address: true #显示IP信息

7、服务的发现:

@EnableDiscoveryClient // 发现服务的注解
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/discovery")
public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String string : services) {
            log.info(string);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance serviceInstance : instances) {
            log.info(serviceInstance.getServiceId() + "\r\n" + serviceInstance.getHost() + "\r\n" + serviceInstance.getPort() + "\r\n" + serviceInstance.getUri());
        }
        return this.discoveryClient;
}

可以自己组装数据返回给前端,这样别人访问你/discovery,就可以知道名为CLOUD-PAYMENT-SERVICE的服务有几个,端口是什么,ip是什么等信息。

8、eureka自我保护机制:
当某个服务不能用了,eureka不会立即清理门户,依旧会保存该微服务的信息,这就是eureka自我保护机制。如果你想当某个服务不能用了,eureka就立即干掉该服务的信息,那么在eureka server中加上相关配置即可。上面的7001和7002都关闭了自我保护,它们的yml中最后那段配置就是这个作用。

四、服务的注册与发现之zookeeper

zookeeper与dubbo天生是一对,springCloud也对zookeeper提供了支持。关于zookeeper,可以参考我zookeeper的文章。下面开始讲如何使用zookeeper代替eureka。
1、首先启动centos上的zookeeper,然后新建名为cloud-provider-payment8004的module:

和8001的pom基本一致,只需要将eureka的依赖替换成zookeeper的依赖,并且将mybatis和mysql相关依赖去掉,本项目为了简单些不再连数据库:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
server:
  port: 8004
  
spring:
  application:
    name: cloud-provider-payment
  cloud:
    zookeeper:
      connect-string: 192.168.0.104:2181 #如果zookeeper是集群,这里用逗号隔开就行了
@SpringBootApplication
@EnableDiscoveryClient // 发现服务
public class PaymentMain8004 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8004.class, args);
    }
}
@RestController
@RequestMapping("/payment")
public class PaymentController {

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

    @GetMapping("/zk")
    public String paymentzk() {
        return "该服务端口号为:" + port;
    }
}
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
   <exclusions>
      <exclusion>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
      </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.5.5</version>
</dependency>

先来看启动前我zookeeper下只有activemq和zookeeper两个节点:

zookeeper

payment8004成功启动后,zookeeper下就会多一个节点,如下:

zookeeper

可以看到多了一个services节点,并且该节点下有我们配置的服务名,说明成功注册到zookeeper中。值得注意的是,zookeeper里的services节点是临时节点,即如果你把payment8004关闭,zookeeper在心跳时间内没有收到回应,就会把该节点干掉。

2、新建名为cloud-consumerzk-order80的module,作为消费端:

@RestController
@RequestMapping("/order")
public class OrderZkController {
    private static final String URL = "http://cloud-provider-payment";
    
    @Autowired
    public RestTemplate restTemplate; 
    
    @GetMapping("/info")
    public String paymentInfo() {
        return restTemplate.getForObject(URL + "/payment/zk", String.class);
    }
}
通过zookeeper调用成功
上一篇 下一篇

猜你喜欢

热点阅读