• 服务发现


    服务发现:可以使用工具类根据服务名称获取对应的服务地址列表。

    实现步骤

    1. 添加依赖
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
    
    
    1. 在主类中添加注解,开启Eureka客户端功能
    @EnableDiscoveryClient
    
    1. 配置application.yml文件
    server:
      port: 8080
    
    spring:
      application: #应用名
        name: consumer
    
    eureka:
      client:
        service-url:
    #      eureka地址
          defaultZone: http://127.0.0.1:10086/eureka
    

    4)编写controller类(这里要注意DiscoveryClient的包,有两个相似的,容易导错,应该是import org.springframework.cloud.client.discovery.DiscoveryClient;)

    package com.consumer.consumertest.controller;
    
    import com.consumer.consumertest.pojo.User;
    import com.netflix.appinfo.InstanceInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.client.ServiceInstance;
    import org.springframework.cloud.client.discovery.DiscoveryClient;
    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 java.util.List;
    
    @RestController
    @RequestMapping("/con")
    public class ConsumerCon {
    
        @Autowired
        RestTemplate restTemplate;
    
        @Autowired
        DiscoveryClient discoveryClient;
    
        @GetMapping("/{id}")
        public User tt(@PathVariable int id) {
            String url = "http://localhost:9091/user/" + id;
    
    //        获取eureka中注册的user-service实例列表
            List<ServiceInstance> serviceInstancesList = discoveryClient.getInstances("user-service");
            ServiceInstance serviceInstance = serviceInstancesList.get(0);
    
    //        动态生成url
            url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" + id;
    
    
            return restTemplate.getForObject(url, User.class);
        }
    
    
    }
    
    
  • 相关阅读:
    webdriver css选取器
    LoadRunner录制下载文件
    LoadRunner结果分析笔记
    LR数据收集分析 Analysis 笔记2。
    Analysis 图的设置与操作。
    LR数据收集分析 Analysis 笔记1。
    unittest学习
    LR几个常用函数
    WebService 测试,参数本身就是XML
    在FlashBulider上安装Android开发环境
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/14668579.html
Copyright © 2020-2023  润新知