微服务4:Eureka客户端集群与负载均衡

229 阅读2分钟
  1. 构建要被集群的单机客户端模块(此处以支付模块作为消费提供者进行测试)
  2. 同步复制单机客户端模块的pom依赖(PaymentModule的pom——>PaymentClusterModule的pom)
  3. 修改集群客户端yml的端口号(应用名不变更,保持为PaymentClusterModuleService)
  4. 修改集群客户端的主启动类(添加Eureka客户端注册注解@EnableEurekaClient
  5. 同步复制单机客户端的业户类(PaymentModule——>PaymentClusterModule)
  6. 分别修改单机和集群的Controller,增加端口号提示说明(看个人选择)
    @Value("${server.port}")
    private String serverPort;
  1. 依次启动客户端集群,查看Eureka注册中心验证

  1. 使用RestTemplate进行接口调用验证
    1. 引入RestTemplate组件,在主启动类中加入以下代码或者单独写Config配置类

注意:不进行装配而直接引用会出现:A component required a bean of type 'org.springframework.web.client. RestTemplate' that could not be found.报错信息

    @Bean
    @LoadBalanced//使用此注解赋予RestTemplate负载均衡的能力,采用轮询方式请求
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
    1. 消费者Controller编写
package com.zhigong.orders.controller;


import com.zhigong.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
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 javax.annotation.Resource;

/**
 * @author TL
 * @create 2022-03-08 17:48
 * @Description
 */
@Api(tags = "订单信息Api")
@RestController
@RequestMapping("OrderInfo")
public class OrderInfoController {

    @Resource
    private RestTemplate restTemplate;

    public static final String PAYMENT_URL = "http://PAYMENTMODULESERVICE";//因为使用消费提供集群,所以不能指定对用端口号,而改用为注册在Eureka注册中的消费提供集群应用名

    @ApiOperation("消费者测试")
    @GetMapping("consumerTest")
    public Result consumerTest(){
        return restTemplate.getForObject(PAYMENT_URL+"/api/wx-pay/consumerProviderTest/",Result.class);
    }
}

RestTemplateRestTemplateRestTemplate

  1. 效果验证:

  1. 完善actuator(监控设置)
    1. Eureka注册中心服务名称修改
    2. 使访问信息存在ip信息提示和指向

操作方式:在yml配置中的Eureka配置参数追加instance设置

注意:经真实测试,只设置prefer-ip-address: trueSpring就会自动为我们获取第一个非回环IP地址,经测试并不能正确有效获取本机ip(存疑);增设手动设置ip-address时,如果设置eureka.instance.prefer-ip-address为false时,那么注册到Eureka中的Ip地址就是本机的Ip地址(还是local host,没啥卵用);如果设置了true并且也设置了eureka.instance.ip-address=手动添加的ip,那么就将此手动设置ip值注册到Eureka中。