【微服务】Spring Cloud中如何使用Eureka
在Spring Cloud中使用Eureka需要以下步骤:
添加依赖:确保你的
pom.xml
或build.gradle
文件中包含Spring Cloud Eureka的依赖。对于Maven项目,在
pom.xml
中添加:<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies>
对于Gradle项目,在
build.gradle
中添加:dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server' }
配置Eureka服务器:在你的
application.properties
或application.yml
文件中配置Eureka服务器。application.properties
配置示例:spring.application.name=eureka-server server.port=8761 eureka.instance.hostname=localhost eureka.client.registerWithEureka=false eureka.client.fetchRegistry=false eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
application.yml
配置示例:spring: application: name: eureka-server server: port: 8761 eureka: instance: hostname: localhost client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
启动类添加注解:在你的启动类上添加
@EnableEurekaServer
注解。import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
服务提供者配置:在服务提供者的
application.properties
或application.yml
中配置Eureka,使其能够发现和注册服务。spring: application: name: service-provider server: port: 8080 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
服务消费者配置:类似地,在服务消费者的配置中指定Eureka服务器地址,以发现服务。
spring: application: name: service-consumer server: port: 8081 eureka:
评论已关闭