如何从eureka-server上进行服务发现,负载均衡远程调用服务

  1. 在spring cloud的maven的pom文件中添加eureka-client的依赖坐标
    1.

    XML 复制代码
            <!--eureka-client依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
  2. 添加运行服务的名称以及eureka-server的地址
    1.

    html 复制代码
    eureka:
      client:
        service-url:
          defaultZone: http://127.0.0.1:9000/eureka
    spring:
      application:
        #应用的名称,可选
        name: order-service
  3. 需要在RestTemplate这个Bean添加一个@LoadBalanced注解,实现负载均衡策略
    1.

    java 复制代码
    package com.app.order.config;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;
    
    /**
     * webmvc的相关配置
     *
     * @author Administrator
     */
    @Configuration
    @Slf4j
    public class WebMvcConfig {
    
        /**
         * 注入RestTemplate的Bean
         *
         * @return 返回RestTemplate
         */
        @LoadBalanced
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    
    }
  4. 在调用远程服务的方法处自动注入RestTemplate,用远程调用的对象服务名代替服务IP地址以及端口号,比如当前示例中需要远程调用user-service的API接口,可这样调用
    1.

    java 复制代码
                // 远程查找用户服务获取用户名信息
                // url地址
                // String url = "http://127.0.0.1:8080/users/" + order.getUserId();
                String url = "http://user-service/users/" + order.getUserId();
                // 发起远程调用
                ResultBean resultBean = restTemplate.getForObject(url, ResultBean.class);
  5. 当前示例中user-service的服务实例有两台,注册到eureka-server服务中,启动服务进行远程调用后,服务可以正常运行,在不改变负载均衡算法的前提下,默认的负载均衡算法是轮询

相关推荐
云飞云共享云桌面2 天前
单机建模卡顿运维繁琐!中小型机械制造厂云飞云 3D 云桌面落地
运维·服务器·网络·3d·自动化·电脑·负载均衡
吠品2 天前
PHP里取月份最后一天的几种方式
java·开发语言·eureka
spider_xcxc2 天前
告别单点故障:阿里云CLB负载均衡从入门到实战
阿里云·云计算·负载均衡
逆向编程3 天前
MySQL 负载均衡完整入门实战教程
mysql·adb·负载均衡
十年磨一剑~4 天前
docker 为何每次 docker tag才能 docker push
docker·容器·eureka
Token炼金师4 天前
服务的骨架:网关、负载均衡、容灾、弹性与多机房 —— 推理系统架构五柱
人工智能·系统架构·llm·负载均衡·容灾·kv cache·prefix cache
章老师说5 天前
NGINX官方谈Lua风险:这其实是两条网关技术路线之争
运维·nginx·负载均衡·lua·openresty
LiaoWL1235 天前
【SpringCloud合集-02】Spring Cloud LoadBalancer 负载均衡器学习笔记
学习·spring cloud·负载均衡
姚不倒6 天前
F5 SSL Profile 证书卸载深入篇
运维·网络协议·负载均衡·ssl·f5
oscar9996 天前
3.4 Nginx 负载均衡——动态再平衡的反人性纪律
nginx·github·负载均衡·财富源代码