环境准备

确保已安装以下工具:JDK 8或更高版本、Maven或Gradle构建工具、VSCode及扩展包(Java Extension Pack、Spring Boot Extension Pack)。VSCode可通过插件市场直接搜索安装扩展。

创建Spring Boot项目

打开VSCode,使用快捷键Ctrl+Shift+P调出命令面板,输入Spring Initializr,选择Create a Maven ProjectCreate a Gradle Project。按向导选择:

  • 语言:Java
  • 依赖:Spring Boot版本选稳定版(如3.x),添加Spring WebEureka Server依赖。
  • 项目名称:如eureka-server

生成项目后,VSCode会自动加载依赖。若未自动下载,在终端执行mvn installgradle build

配置Eureka Server

src/main/resources/application.properties中配置:

server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
spring.application.name=eureka-server

若使用YAML格式,创建application.yml

server:
  port: 8761
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
spring:
  application:
    name: eureka-server

启用Eureka Server注解

在主启动类(通常位于src/main/java/com/example/eurekaserver)上添加@EnableEurekaServer

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

启动与验证

在VSCode终端运行项目:

  • Maven项目:mvn spring-boot:run
  • Gradle项目:gradle bootRun

访问http://localhost:8761,若看到Eureka控制台页面且Instances currently registered with Eureka为空列表,表示服务端已就绪。

注册微服务到Eureka

以另一个Spring Boot项目(如user-service)为例,需添加Eureka Client依赖。配置其application.properties

server.port=8081
spring.application.name=user-service
eureka.client.service-url.defaultZone=http://localhost:8761/eureka

主类添加@EnableEurekaClient(Spring Cloud新版本可不加),启动后刷新Eureka控制台,可见服务已注册。

高可用配置(可选)

搭建多节点Eureka Server时,修改配置文件:

# 节点1配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://peer2:8762/eureka
spring:
  profiles: peer1
server:
  port: 8761

# 节点2配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://peer1:8761/eureka
spring:
  profiles: peer2
server:
  port: 8762

通过--spring.profiles.active=peer1启动不同实例。

安全认证(可选)

添加Spring Security依赖,配置application.properties

spring.security.user.name=admin
spring.security.user.password=123456
eureka.client.service-url.defaultZone=http://admin:123456@localhost:8761/eureka

同时需配置安全类继承WebSecurityConfigurerAdapter并重写configure方法。

常见问题排查

  • 无法访问控制台:检查防火墙或端口占用,使用netstat -ano(Windows)或lsof -i:8761(Mac/Linux)。
  • 服务未注册:确认客户端配置的defaultZone与服务器地址一致,检查网络连通性。
  • 依赖冲突:通过mvn dependency:tree分析依赖树,排除冲突库。
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐