天天看点

Spring boot 2.0 + Eureka Client 搭建

  1. POM.xml

<

<properties>
	<java.version>1.8</java.version>
	<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<!--添加Eureka server依赖-->
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
	<dependency>
	     <groupId>org.springframework.cloud</groupId>
	     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	</dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>


<repositories>
	<repository>
		<id>spring-milestones</id>
		<name>Spring Milestones</name>
		<url>https://repo.spring.io/libs-milestone</url>
		<snapshots>
			<enabled>false</enabled>
		</snapshots>
	</repository>
</repositories>
           
  1. application.properties.

    #spring boot with Eureka client

server.port=17002

spring.application.name=hello-service

eureka.client.serviceUrl.defaultZone=http://localhost:7002/eureka/

  1. application

    package com.example.demo;

    import java.util.List;
     
     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.RequestMapping;
     import org.springframework.web.bind.annotation.RequestMethod;
     import org.springframework.web.bind.annotation.RestController;
     
     
     @RestController
     public class HelloController {
     	@Autowired
     	private DiscoveryClient client;
     	
     	@RequestMapping(value="/hello", method=RequestMethod.GET)
     	public String index() {
     		List<ServiceInstance> instance = client.getInstances("hello-service");
     		
     		System.out.println("Controller starting...");
     		System.out.println("getHost:" + instance.get(0).getHost());
     		System.out.println("getServiceId:" + instance.get(0).getServiceId());
     		System.out.println("getPort:" + instance.get(0).getPort());
     		System.out.println("getUri:" + instance.get(0).getUri());
     		return "Hello world";
     	}
     }