SpringCloud学习(六):微服务集群配置

大数据26

在上文中我们实现了eureka的集群,就相当于用户、服务和中间商中,我们连系了多个中间商,这样假如一个中间商跑路了,我们还能够通过其他中间商访问到服务。
那么,假如服务坏了呢?肯定不能只有一个服务,我们也需要给他找几个"备胎"
所以,我们需要实现服务的集群

一、创建module

参考8001,创建8002

二、修改pom文件


        cloud
        com.shang.cloud
        1.0-SNAPSHOT

    4.0.0

    cloud-provider-payment8002

            org.springframework.cloud
            spring-cloud-starter-zipkin

            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client

            com.shang.cloud
            cloud-api-commons
            ${project.version}

            org.springframework.boot
            spring-boot-starter-web

            org.springframework.boot
            spring-boot-starter-actuator

            org.mybatis.spring.boot
            mybatis-spring-boot-starter

            com.alibaba
            druid
            1.0.20

            mysql
            mysql-connector-java

            org.springframework.boot
            spring-boot-starter-jdbc

            org.springframework.boot
            spring-boot-devtools
            runtime
            true

            org.projectlombok
            lombok
            true

            org.springframework.boot
            spring-boot-starter-test
            test

三、编写yml文件

与8001一致,只是端口号修改为8002即可

server:
  port: 8002

spring:
  application:
    name: cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root

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

mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.springcloud.entities    # 所有Entity别名类所在包

四、编写主启动类

与8001一致,修改类名即可。

五、修改8001和8002的controller

为了能看出我们访问的是哪个服务,我们在controller中加上端口号的属性,并打印出来

SpringCloud学习(六):微服务集群配置

六、修改80服务的业务代码

因为我们现在实现了负载均衡,有多个服务,所以OrderController 中的URL不能写死了。我们将在eureka中注册的服务名作为URL

SpringCloud学习(六):微服务集群配置

同时应该使用@LoadBalanced注解赋予RestTemplate负载均衡的能力 。

七、运行测试

先在浏览器地址栏输入

http://eureka7001.com:7001/

http://eureka7002.com:7002/

SpringCloud学习(六):微服务集群配置

再输入

http://localhost:8001/payment/get/1

http://localhost:8002/payment/get/1

SpringCloud学习(六):微服务集群配置

最后输入

http://localhost:90/consumer/payment/get/1

SpringCloud学习(六):微服务集群配置

SpringCloud学习(六):微服务集群配置

可以看到,8001和8002端口在刷新之后交替出现(轮询)

Original: https://blog.csdn.net/m0_49499183/article/details/120918258
Author: 玉面大蛟龙
Title: SpringCloud学习(六):微服务集群配置