如何从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服务中,启动服务进行远程调用后,服务可以正常运行,在不改变负载均衡算法的前提下,默认的负载均衡算法是轮询

相关推荐
java_logo1 天前
SGLANG Docker容器化部署指南
linux·运维·docker·容器·eureka·1024程序员节
斯普信专业组2 天前
Docker 常用命令与时区配置指南
docker·容器·eureka
梁正雄2 天前
6、prometheus资源规划
运维·服务器·服务发现·prometheus·监控
return(b,a%b);2 天前
docker拉取失败,更换docker的源
docker·容器·eureka
梁正雄3 天前
4、prometheus-服务发现k8s api-2
kubernetes·服务发现·prometheus
Knight_AL3 天前
Docker 加载镜像时报 no space left on device 的彻底解决方案
docker·容器·eureka
IT小哥哥呀3 天前
Nginx高可用配置实战:负载均衡 + 健康检查 + 动态扩展
运维·nginx·负载均衡·devops·日志分析·openresty·动态扩展
半梦半醒*3 天前
k8s——pod详解2
linux·运维·docker·容器·kubernetes·负载均衡
hu1j3 天前
[HTB] 靶机学习(十二)Eureka
学习·安全·web安全·网络安全·云原生·eureka