zoukankan      html  css  js  c++  java
  • 服务发现

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

    实现步骤

    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);
        }
    
    
    }
    
    
  • 相关阅读:
    Servlet页面跳转实现方法的区别
    谈JSP与XML的交互
    xml可以用做什么?
    Struts1.2入门知识
    做java web 开发的简单项目必须具备的知识
    Web工程师必备的18款工具
    css的四种调用方式
    jQuery Utilities
    历年考研数学常考题型考试必备
    。net思维导图
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/14668579.html
Copyright © 2011-2022 走看看