【微服务】Spring Cloud中如何使用Eureka
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                在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:
评论已关闭