springcloud学习笔记-消费者通过注册中心服务列表获取服务

1.创建子工程并导入依赖



    
        ssmspringboot2
        com.example
        0.0.1-SNAPSHOT
    
    4.0.0

    provider-service

    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                
                Edgware.SR4
                pom
                import
            
        
    
    
        
            
                src/main/resources
                
                    **/*.yml
                
            
        
    

2.配置application.yml文件

server:
  port: 8890
spring:
  application:
    name: consumer-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8888/eureka/
  instance:
    hostname: localhost
    prefer-ip-addrss: false  #使用ip地址注册

3.配置启动类

在启动类上面添加注解 @EnableEurekaServer

@EnableEurekaClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }
}

4.注入DisCoveryClient,进行远程调用

package test.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.client.http.HttpRequest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import test.entity.Student;

import java.util.List;

@Controller
public class testController {
    @Autowired
    private DiscoveryClient product;
    @RequestMapping("test")
    @ResponseBody
    public String test(HttpRequest req, Model model){
        List instances = product.getInstances("PROVIDER-SERVICE");
        ServiceInstance serviceInstance = instances.get(0);
        RestTemplate r = new RestTemplate();
        String x = r.getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/test", Student.class).toString();
        return x;
    }
}

4.微服务调用成功

在这里插入图片描述

你可能感兴趣的:(java,spring,cloud,学习,eureka,spring,boot,开发语言)