Java如何使用Eureka代码示例

95 阅读1分钟

1、添加Maven依赖

首先,在pom.xml中添加Eureka客户端的依赖:

<dependencies>
    <!-- Spring Boot Starter for Eureka Client -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <!-- 其他依赖... -->
</dependencies>

<!-- 确保你的Spring Cloud版本与Eureka版本兼容 -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>你的Spring Cloud版本号,例如Greenwich.SR3</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2、 配置application.yml或application.properties

在application.yml中配置Eureka客户端:

spring:
  application:
    name: my-service # 服务名称
  cloud:
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/ # Eureka服务端的地址
      instance:
        hostname: localhost # 服务的hostname,如果不配置则使用IP地址
        instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} # 自定义instance-id,方便识别

3、启动类上添加@EnableDiscoveryClient注解

在Spring Boot的启动类上添加@EnableDiscoveryClient注解,以启用Eureka客户端:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class MyServiceApplication {

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

}

4、 编写服务调用代码

使用DiscoveryClient接口来获取服务列表和实例信息。以下是一个简单的示例:

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.RestController;

import java.util.List;

@RestController
public class MyServiceController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/services")
    public List<String> getServices() {
        return discoveryClient.getServices(); // 获取所有服务名列表
    }

    @GetMapping("/service-instances/{serviceName}")
    public List<ServiceInstance> getServiceInstances(@PathVariable String serviceName) {
        return discoveryClient.getInstances(serviceName); // 根据服务名获取实例列表
    }
}

现在,当启动Spring Boot应用时,会自动向配置的Eureka服务器注册。可以通过Eureka的管理界面来查看已注册的服务,并通过上面的REST接口来获取服务列表和实例信息。